Search code examples
c++c++11initializationunique-ptrinitializer-list

Any way to initialize a vector of unique_ptr?


For example

struct A
{
    vector<unique_ptr<int>> m_vector { make_unique<int>(1), make_unique<int>(2) };
};

I try above but failed. Any way to initialize a vector of unique_ptr?


Solution

  • You can't move from an initializer list because the elements are const. §8.5.4 [dcl.init.list]/p5:

    An object of type std::initializer_list<E> is constructed from an initializer list as if the implementation allocated an array of N elements of type const E, where N is the number of elements in the initializer list. Each element of that array is copy-initialized with the corresponding element of the initializer list, and the std::initializer_list<E> object is constructed to refer to that array.

    You can only copy, but you can't copy a unique_ptr since it's move-only.

    You'd have to use push_back or emplace_back etc. to fill the vector after you construct it.