Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Insert the whole vector<unique_ptr> as element in other vector

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading