vector< unique_ptr>的唯一副本 [英] Unique copy of vector<unique_ptr>

查看:91
本文介绍了vector< unique_ptr>的唯一副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 vector< unique_ptr> 的类对象。我想要此对象的副本在其上运行非const函数。原始副本必须保持 const

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

此类的副本构造函数是什么样的?

What would the copy constructor for such a class look like?

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

 std::vector<std::unique_ptr> ptrs;
};


推荐答案

您不能简单地复制 std :: vector< std :: unique_ptr> ,因为 std :: unique_ptr 是不可复制的,因此它将删除向量复制构造函数。

You cannot simply copy a std::vector<std::unique_ptr> because std::unique_ptr is not copyable so it will delete the vector copy constructor.

如果不更改存储在向量中的类型,则可以通过创建全新的向量(如

If you do not change the type stored in the vector then you could make a "copy" by creating a whole new vector like

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

现在来自,并且可以独立更改。

Now to is a separate copy of from and can be changed independently.

另外:如果您输入的是是多态的,以上将无法正常工作,因为您将拥有一个指向基类的指针。您需要做的是创建一个虚拟的 clone 成员函数,并让 clone 返回一个 std :: unique_ptr 到实际派生对象的副本。这将使代码看起来像这样:

Additionally: If your type is polymorphic the above won't work as you would have a pointer to the base class. What you would have to do is make a virtual clone member function and have clone return a std::unique_ptr to a copy of the actual derived object. That would make the code look like:

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());

这篇关于vector&lt; unique_ptr&gt;的唯一副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆