Any way to initialize a unique_ptr vector?

for example

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

      

I tried above but couldn't. Any way to initialize a unique_ptr vector?

+3


source to share


1 answer


You cannot go from the initializer list because the elements const

. §8.5.4 [dcl.init.list] / p5:

A type object std::initializer_list<E>

is constructed from list initializer as if the implementation had allocated an array of N

elements of type const E

, where N is the number of elements in the initializer list. Each element of this array is initialized with a corresponding element in the initializer list and an Object is std::initializer_list<E>

created to indicate that it is an array.



You can only copy a copy, but you cannot copy unique_ptr

as it only moves.

You will need to use push_back

or emplace_back

etc. to fill the vector after you create it.

+6


source







All Articles