2

How to initialize a vector of a structure with unique_ptr? For example:

#include <memory> #include <vector> using namespace std; struct A { int i; unique_ptr<int> p; }; int main() { vector<A> v{ { 10, make_unique<int>(10) } }; // error above: cannot convert from initializer-list to vector<A> return 0; } 
0

1 Answer 1

2
vector<A> v{ { 10, make_unique<int>(10) } }; 

Within the inner braces of the statement above you're aggregate initializing an instance of A, so far so good.

But now there's no way to move this instance out of the initializer list, the only this you can do is copy the object. However, copying will fail because the compiler generated copy constructor for A is implicitly deleted because of the unique_ptr data member. Hence the compilation error.

The only way around this is to not use a braced-init-list. Instead construct an instance of A and then use

v.push_back(std::move(a)); 
Sign up to request clarification or add additional context in comments.

3 Comments

Or you could create a copy constructor for A.
@AndyG Sure, but how do you handle a unique_ptr within a copy-constructor? Making a copy of the object being pointed to seems kinda odd, but you could do that.
Yes, via copying. In OPs case, we're only copying an int.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.