deep copy and dynamic cast unique_ptr

2019-09-06 03:40发布

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:

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

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. Can someone help me with this?

1条回答
啃猪蹄的小仙女
2楼-- · 2019-09-06 04:08

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.
}
查看更多
登录 后发表回答