C++:深度复制Base类指针

mad*_*adu 21 c++ inheritance deep-copy copy-constructor

我四处搜索,似乎为了执行此操作,我需要更改我的Base类,并想知道这是否是最好的方法.例如,我有一个Base类:

class Base {}
Run Code Online (Sandbox Code Playgroud)

然后是一长串派生类:

class Derived_1:: public Base {}
class Derived_2:: public Derived_1{}
...
...
class Derived_n:: public Derived_M{}
Run Code Online (Sandbox Code Playgroud)

然后我又上了一堂课:

class DeepCopy 
{ 
  Base * basePtr;

  public:
   DeepCopy(DeepCopy & dc) {}
}
Run Code Online (Sandbox Code Playgroud)

假设Base类和Derived_x类复制构造函数已正确编码,那么为DeepCopy编写复制构造函数的最佳方法是什么.我们如何知道我们要复制的对象的basePtr中的类?

我能想到的唯一方法就是使用RTTI,但是使用一长串的dynamic_cast似乎不对.此外,它需要DeepCopy来了解Base类的继承层次结构.

我看到的另一种方法是在这里.但它需要Base和Derived类实现克隆方法.

那么有一个更简单,标准的方法吗?

Dav*_*eas 27

您需要使用虚拟副本模式:在执行复制的接口中提供虚拟功能,然后跨层次结构实现它:

struct base {
   virtual ~base() {}                // Remember to provide a virtual destructor
   virtual base* clone() const = 0;
};
struct derived : base {
   virtual derived* clone() const {
      return new derived(*this);
   }
};
Run Code Online (Sandbox Code Playgroud)

然后该DeepCopy对象只需要调用该函数:

class DeepCopy 
{ 
  Base * basePtr;    
public:
   DeepCopy(DeepCopy const & dc)           // This should be `const`
      : basePtr( dc.basePtr->clone() )
   {}
};
Run Code Online (Sandbox Code Playgroud)


jog*_*pan 22

使用采用clone()函数的方法是一个很好的解决方案.注意使用CRTP(奇怪的重复模板模式)可以为您节省一些工作.你这样做的方法是引入一个中间级别(BaseCRTP下面称为),它是一个模板并实现了这个clone()功能.在派生实际类时,将它们用作派生它们的基础的模板参数.他们将clone()自动获得为其实现的功能.确保派生类实现了一个复制构造函数(或者确保默认值是你需要的).

/* Base class includes pure virtual clone function */
class Base {
public:
  virtual ~Base() {}
  virtual Base *clone() const = 0;
};

/* Intermediate class that implements CRTP. Use this
 * as a base class for any derived class that you want
 * to have a clone function.
 */
template <typename Derived>
class BaseCRTP : public Base {
public:
  virtual Base *clone() const {
      return new Derived(static_cast<Derived const&>(*this));
  }
};

/* Derive further classes. Each of them must
 * implement a correct copy constructor, because
 * that is used by the clone() function automatically.
 */
class Derived1 : public BaseCRTP<Derived1> {
  /*... should have an ordinary copy constructor... */
};

class Derived2 : public BaseCRTP<Derived2> {
  /*... should have an ordinary copy constructor... */
};
Run Code Online (Sandbox Code Playgroud)

然后,您可以DeepCopy通常以通常的方式实现该类:

class DeepCopy 
{ 
  Base *basePtr;    
public:
  DeepCopy(const DeepCopy &dc)
    : basePtr(dc.basePtr->clone())
  {}
};
Run Code Online (Sandbox Code Playgroud)