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;
}
user1899020
  • 13,167
  • 21
  • 79
  • 154

1 Answers1

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));
Praetorian
  • 106,671
  • 19
  • 240
  • 328