I tried to define move constructor Person(Person&&) and delete default one Person() = delete, but I still get std::unique_ptr<Person,std::default_delete<Person>>::unique_ptr(const std::unique_ptr<Person,std::default_delete<Person>> &)': attempting to reference a deleted function.
I tried to manually iterate and move one item at a time, but this didn’t help. What am I missing here?
Attempt
v2.push_back(std::vector<std::unique_ptr<Person>>());
for (const auto& p : v)
{
v2[0].push_back(std::move(p));
}
Code
struct Person
{
std::string name;
Person(std::string name) {}
};
std::vector<std::unique_ptr<Person>> v;
std::vector<std::vector<std::unique_ptr<Person>>> v2;
std::unique_ptr<Person> ptr1 = std::make_unique<Person>("name");
v.push_back(std::move(ptr1));
v2.push_back(v);
>Solution :
There are two issues here, one in each of your code snippets:
for (const auto& p : v)
{
v2[0].push_back(std::move(p));
}
Get rid of the const – you can’t move from a const object (or reference).
And:
v2.push_back(v);
will try to copy v (which you can’t do, because of the unique_ptr aspect), so it needs to be:
v2.push_back(std::move(v));
(assuming that is your intent).