Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 761
user1899020 Avatar asked Sep 13 '14 20:09

user1899020


1 Answers

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.

like image 152
T.C. Avatar answered Oct 11 '22 17:10

T.C.