問題描述
我一直在為這種問題苦苦掙扎,所以我決定在這里提問.
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);
該方法應該返回一個動態(tài)創(chuàng)建的副本,或者至少將對象存儲在某些數據結構中的堆棧上,以避免返回臨時地址"問題.
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 語句中使用多個 typeid
或 dynamic_cast
來檢查每個可能的派生類型,然后使用 new
運算符.還有其他更好的方法嗎?
The naive approach to implement the above method would be using multiple typeid
s or dynamic_cast
s 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> { ... };
這篇關于如何從指向多態(tài)基類的指針復制/創(chuàng)建派生類實例?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!