jeudi 27 septembre 2018

deep copy with smart pointer-attached inherited objects

I am not sure what the best / cleanest solution to making a deep copy of an object with a smart pointer containing inherited objects is. To boil it down, given the following code

class A {};

class D1 : public A{
public:
    int x1 = 0;
};

class D2 : public A {
public:
    int x2 = 2;
};


class V {
public:
    V(A* a) : ptr(a) {}
    std::unique_ptr<A> ptr;
};    

void run() {
    std::vector<V> v;
    v.push_back(V(new D1));
    v.push_back(V(new D2));
    /// I want to make a deep copy of v here
}

where the vector v contains both objects of type D1 and D2, what is the shortest / most elegant way to make a deep copy of v? I can think of two ways, both with some drawbacks:

  1. create a virtual A* clone() method in the base class and overload it in each inherited class (as described here). Drawback: the clone method needs to be instantiated in every inherited class and there may be multiple.
  2. create a copy constructor/assignment operator for V. Using dynamic_cast<D1/D2>, check which kind of inherited object is attached and make a copy for that specific type. Drawback: one needs to go through all inherited classes in the copy constructor of V.

Aucun commentaire:

Enregistrer un commentaire