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?
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 ofN
elements of typeconst 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 thestd::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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With