如何从指向多态基类的指针复制/创建派生类实例

How to copy/create derived class instance from a pointer to a polymorphic base class?

本文关键字:复制 创建 派生 实例 指针 基类 多态      更新时间:2023-10-16

我已经为这类问题挣扎了很长时间,所以我决定在这里问一下。

class Base {
  virtual ~Base();
};
class Derived1 : public Base { ... };
class Derived2 : public Base { ... };
...
// Copies the instance of derived class pointed by the *base pointer
Base* CreateCopy(Base* base);

该方法应该返回一个动态创建的副本,或者至少将对象存储在堆栈中,以避免"返回临时地址"问题。

实现上述方法的朴素方法是在一系列if语句中使用多个typeid s或dynamic_cast s来检查每个可能的派生类型,然后使用new运算符。有没有其他更好的方法?

注::我知道,这个问题可以避免使用智能指针,但我感兴趣的是简约的方法,没有一堆库。

在基类中添加virtual Base* clone() const = 0;,并在派生类中适当地实现它。如果您的Base不是抽象的,您当然可以调用它的复制构造函数,但这有点危险:如果您忘记在派生类中实现它,您将获得(可能不想要的)切片。

如果您不想重复这些代码,您可以使用CRTP习惯用法通过模板实现该函数:

template <class Derived>
class DerivationHelper : public Base
{
public:
  virtual Base* clone() const
  {
    return new Derived(static_cast<const Derived&>(*this)); // call the copy ctor.
  }
};
class Derived1 : public DerivationHelper <Derived1> { ... };
class Derived2 : public DerivationHelper <Derived2> { ... };

另一种方法是在每个派生类中实现的公共基中有一个纯虚拟CreateCopy()方法。

相关文章: