我想在下面的类A上实现一个拷贝构造函数,它包含一个指向多态实现类Base的指针。目前,我在类Base中有一个虚拟的create_copy()方法,派生类需要重写。但是,派生类的覆盖全部使用完全相同的代码。我错过了一种更简单的方法来复制类型A的对象吗?我真的需要为每个派生类复制完全相同的代码吗?以下是我现在使用的。如果它改变了答案,则需要运行时多态性。如何统一实现派生类的拷贝构造函数?
class A {
public:
A(const A& a): base_p {a.base_p->create_copy()} {}
private:
unique_ptr<Base> base_p;
};
class Base {
public:
virtual unique_ptr<Base> create_copy() const;
};
class Derived : public Base {
public:
unique_ptr<Base> create_copy() const override {
return make_unique<Derived>(*this);
}
};
一个想法像使用一些代码,我曾参与:
return make_unique<remove_reference_t<decltype(*this)>>(*this);
然而,这段代码不能在一个const成员函数的工作。另外,我认为我仍然必须显式重写每个派生类中的create_copy()方法,因为decltype(* this)是在编译时计算的,因此将该代码放入基类方法中对我没有任何好处。
编辑: 在Inheritance in curiously recurring template pattern polymorphic copy (C++)答案比我所需要的更复杂。我有一个简单的 深度1的继承层次结构,应该永远不需要扩展到更大的深度。 Iorro的答案和提供的链接足以解决我的问题。
您可能有兴趣[本文](https://stackoverflow.com/questions/196733/how-can-i-use-covariant-return-types-with-smart-pointers) – CoryKramer
可能的重复[奇怪的循环模板模式中的继承多态复制(C++)](http://stackoverflow.com/questions/9422760/inheritance-in-curiously-recurring-template-pattern-polymorphic-copy-c) –
设计是否真的需要一个'unique_ptr',其中的内容在每个副本都被克隆! –