简体   繁体   中英

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:

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.

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.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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