Unique copy of the vector <unique_ptr>

I have a class object that contains vector<unique_ptr>. I want a copy of this object to run non-constant functions. The original copy must remain const .

What does the copy constructor look like for this class?

class Foo{
public:
 Foo(const Foo& other): ??? {}

 std::vector<std::unique_ptr> ptrs;
};
+4
source share
1 answer

You cannot just copy std::vector<std::unique_ptr>because it is std::unique_ptrnot copied, so it will remove the vector copy constructor.

If you do not change the type stored in the vector, you can make a “copy” by creating a whole new vector, for example

std::vector<std::unique_ptr<some_type>> from; // this has the data to copy
std::vector<std::unique_ptr<some_type>> to;

for (const auto& e : from)
    to.push_back(std::make_unique<some_type>(*e));

to from .

+8

Source: https://habr.com/ru/post/1624333/


All Articles