vector <unique_ptr>的唯一副本

Wil*_*oat 8 c++ copy vector unique-ptr

我有一个包含a的类对象vector<unique_ptr>.我想要一个这个对象的副本来运行非const函数.原始副本必须保持const.

这样一个类的复制构造函数会是什么样的?

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

 std::vector<std::unique_ptr> ptrs;
};
Run Code Online (Sandbox Code Playgroud)

Nat*_*ica 13

你不能简单地复制一个std::vector<std::unique_ptr>因为std::unique_ptr不可复制,所以它将删除矢量复制构造函数.

如果你不改变存储在矢量中的类型,那么你可以通过创建一个全新的矢量来制作一个"副本"

std::vector<std::unique_ptr<some_type>> from; // this has the data to copy
std::vector<std::unique_ptr<some_type>> to;
to.reserve(from.size()) // preallocate the space we need so push_back doesn't have to

for (const auto& e : from)
    to.push_back(std::make_unique<some_type>(*e));
Run Code Online (Sandbox Code Playgroud)

现在to是一个单独的副本,from可以单独更改.


另外:如果你的类型是多态的,那么上面的代码将不起作用,因为你有一个指向基类的指针.您需要做的是创建一个虚拟clone成员函数并clone返回一个std::unique_ptr实际派生对象的副本.这将使代码看起来像:

std::vector<std::unique_ptr<some_type>> from; // this has the data to copy
std::vector<std::unique_ptr<some_type>> to;
to.reserve(from.size()) // preallocate the space we need so push_back doesn't have to

for (const auto& e : from)
    to.push_back(e->clone());
Run Code Online (Sandbox Code Playgroud)

  • @MatthieuH 这是可能的。但这通常是一个设计缺陷。 (2认同)