简体   繁体   English

深拷贝和动态转换 unique_ptr

[英]deep copy and dynamic cast unique_ptr

Suppose I have a class like the following:假设我有一个如下所示的类:

class A { virtual ~A(); ... }
class B : public A { ... }
class C : public A { ... }

I also have a vector of unique_ptr which is declared this way:我还有一个以这种方式声明的 unique_ptr 向量:

std::vector<std::unique_ptr<A>> vec;

Assume vec is populated with unique_ptr to objects of derived class.假设 vec 用 unique_ptr 填充到派生类的对象。 What should I do if I want a deep copy of any of the vector elements, either b or c, and let a base class unique_ptr pointing to it?如果我想要任何向量元素(b 或 c)的深层副本,并让基类 unique_ptr 指向它,我该怎么办? Originally I was doing things like最初我在做类似的事情

std::unique_ptr<A> tmp = std::make_unique<A>(*b);

I don't think this is correct.我不认为这是正确的。

One possible solution is to declare a virtual cloning method in the base class and override it for each subclass:一种可能的解决方案是在基类中声明一个虚拟克隆方法并为每个子类覆盖它:

class A {
    virtual ~A() {}
    virtual std::unique_ptr<A> clone() const = 0;
}
class B : public A {
    std::unique_ptr<A> clone() const override {
        return std::unique_ptr<A>(new B(*this));
    }
};

Edit:编辑:

An usage example:一个使用示例:

void f(const A& original) {
    std::unique_ptr<A> copy = original.clone();
    // Here, copy points to an instance of class B.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM