0

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);
theateist
  • 13,879
  • 17
  • 69
  • 109
  • 3
    A unique_ptr cannot be copied, like the name says, and you are copying the vector of unique_ptrs 'v' to the vector of vectors of unique_ptrs 'v2'. – Claudiu HBann May 24 '23 at 22:15

1 Answers1

3

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).

Paul Sanders
  • 24,133
  • 4
  • 26
  • 48