复制具有Base类的唯一ptr的类的构造函数 [英] Copy constructor for a class that has unique ptr of a Base class

查看:221
本文介绍了复制具有Base类的唯一ptr的类的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当一个类有一个Base类的unique_ptr时,什么是实现复制构造函数的好方法。

When a class has a unique_ptr of a Base class what is a good way to implement the copy constructor.

让我尝试用一​​个例子解释它:

Let me try to explain it with an example:

struct Base
{
    virtual void doSth() = 0; // to make the class abstract.
};

struct Derived : public Base
{
    virtual void doSth() override {}
};

struct Foo
{
    std::unique_ptr<Base> bar;

    Foo(const Foo& other) : bar(new Base(*other.bar))   // cant do it, its abstract.
    {
        bar = std::move(other.bar); // cant do it, reference object is modified.
    }
};

这里的类是abstract,我不能使用它的拷贝构造函数。并且也不能使用move on一个常量引用(我们不应该做它实际上,不要修改对象)。

Here as the class is abstract i cannot use its copy constructor. and also cannot use move on a constant reference ( we shouldnt do it actually, do not modify the object).

我最终得到的是这样:

struct Base
{
    virtual void doSth() = 0; // to make the class abstract.
};

struct Derived : public Base
{
    virtual void doSth() override {}

    Derived(const Base* b)
    {

    }
};

struct Foo
{
    std::unique_ptr<Base> bar;

    Foo(const Foo& other) : bar(new Derived(other.bar.get()))
    {

    }
};

然而,它感觉不太对,

However, it does not feel quite right, does it?

推荐答案

如果您需要以多态方式复制,您需要在所持有类型的界面中提供。将克隆虚函数添加到 Base ,并使用它创建一个存储在复制的 Foo 中。

If you need to copy polymorphically, you will need to provide that in the interface of the type you are holding. Add a clone virtual function to Base and use that to create a copy that you can store in the copied Foo.

其他选择包括不复制(删除复制构造函数)或使用引用语义(复制引用同一对象:change unique_ptr shared_ptr ),但这两个选项都不提供副本

Other alternatives include not copying (delete the copy constructor) or use reference semantics (copies refer to the same object: change unique_ptr for shared_ptr) but neither of those alternatives really provide copies.

这篇关于复制具有Base类的唯一ptr的类的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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