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

How to copy/create derived class instance from a pointer to a polymorphic base class?(如何从指向多态基类的指针复制/创建派生类实例?)
本文介绍了如何从指向多态基类的指针复制/创建派生类实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我一直在为这种问题苦苦挣扎,所以我决定在这里提问.

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.

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

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.:我知道,使用智能指针可以避免这个问题,但我对没有一堆库的简约方法感兴趣.

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.

推荐答案

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

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.

如果您不想复制该代码,您可以使用 CRTP 惯用语通过模板实现功能:

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)
STL BigInt class implementation(STL BigInt 类实现)
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)