如何从指针到多态基类复制/创建派生类实例? [英] How to copy/create derived class instance from a pointer to a polymorphic base class?

查看:204
本文介绍了如何从指针到多态基类复制/创建派生类实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力解决这种问题很长时间,所以我决定在这里问。

  class Base {
virtual〜Base();
};
class Derived1:public Base {...};
class Derived2:public Base {...};
...

//复制由基本指针指向的派生类的实例
Base * CreateCopy(Base * base);

该方法应该返回动态创建的副本,或者至少将对象存储在堆栈中的某些数据结构中避免返回地址的临时问题。



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



PS:我知道,这个问题可以使用智能指针避免,但我对简约

解决方案

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



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

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

这篇关于如何从指针到多态基类复制/创建派生类实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆