且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-02 17:48:34

你添加一个 virtual Base * clone()const = 0; ,并在Derived类中适当地实现它。如果你的 Base 不是抽象的,你当然可以调用它的复制构造函数,但是有点危险:如果你忘记在派生类中实现它,



如果您不想复制该代码,可以使用 CRTP idiom 通过模板实现该函数:

  template< class Derived&gt ; 
class DerivationHelper:public Base
{
public:
virtual Base * clone()const
{
return new Derived(static_cast< const Derived& ;(*这个)); //调用copy ctor。
}
};

class Derived1:public DerivationHelper< Derived1> {...};
class Derived2:public DerivationHelper< Derived2> {...};


I have been struggling with this kind of problem for a long time, so I decided to ask here.

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);

The method should return a dynamically created copy, or at least store the object on stack in some data structure to avoid "returning address of a temporary" problem.

The naive approach to implement the above method would be using multiple typeids or dynamic_casts in a series of if-statements to check for each possible derived type and then use the new operator. Is there any other, better approach?

P.S.: I know, that the this problem can be avoided using smart pointers, but I am interested in the minimalistic approach, without a bunch of libraries.

You add a virtual Base* clone() const = 0; in your base class and implement it appropriately in your Derived classes. If your Base is not abstract, you can of course call its copy-constructor, but that's a bit dangerous: If you forget to implement it in a derived class, you'll get (probably unwanted) slicing.

If you don't want to duplicate that code, you can use the CRTP idiom to implement the function via a template:

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