深层复制和动态转换unique_ptr [英] deep copy and dynamic cast unique_ptr

查看:241
本文介绍了深层复制和动态转换unique_ptr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类似以下的类:

Suppose I have a class like the following:

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

我也有一个unique_ptr向量,它是这样声明的:

I also have a vector of unique_ptr which is declared this way:

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

假定vec使用unique_ptr填充到派生类的对象.如果我想复制任何向量元素b或c,并让基类unique_ptr指向它,该怎么办?本来我是在做类似的事情

Assume vec is populated with unique_ptr to objects of derived class. 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? 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));
    }
};

一个用法示例:

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

这篇关于深层复制和动态转换unique_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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