如何从指向多态基类的指针复制/创建派生类实例
How to copy/create derived class instance from a pointer to a polymorphic base class?
我已经为这类问题挣扎了很长时间,所以我决定在这里问一下。
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);
该方法应该返回一个动态创建的副本,或者至少将对象存储在堆栈中,以避免"返回临时地址"问题。
实现上述方法的朴素方法是在一系列if语句中使用多个typeid
s或dynamic_cast
s来检查每个可能的派生类型,然后使用new
运算符。有没有其他更好的方法?
注::我知道,这个问题可以避免使用智能指针,但我感兴趣的是简约的方法,没有一堆库。
在基类中添加virtual Base* clone() const = 0;
,并在派生类中适当地实现它。如果您的Base
不是抽象的,您当然可以调用它的复制构造函数,但这有点危险:如果您忘记在派生类中实现它,您将获得(可能不想要的)切片。
如果您不想重复这些代码,您可以使用CRTP习惯用法通过模板实现该函数:
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> { ... };
另一种方法是在每个派生类中实现的公共基中有一个纯虚拟CreateCopy()
方法。
相关文章:
- 创建一个没有复制构造函数的类的 std::vector 的 std::vector
- 如何在新数组较小时创建新数组并将旧数组的最后一个元素复制到新数组中?
- 是否可以/希望创建不可复制的共享指针模拟(以启用weak_ptr跟踪/借用类型语义)?
- C++为具有引用成员变量的类创建复制构造函数
- 在c++中为链接列表创建复制构造函数/函数
- 我可以隐式地创建一个琐碎的可复制类型吗
- 创建用户定义的复制构造函数时无法创建对象
- r-在Rcpp和C++之间转换矢量(使用Rcpp::as或Rcpp:::wrap)是否会创建一个新的矢量并复制元素
- 有没有一种方法可以在不复制数据的情况下从string_view创建字符串流
- 为什么从引用创建共享指针会复制对象?
- 创建子类复制构造函数时是否强制使用/创建默认的超级构造函数?[C++]
- 创建 std::set 只复制一个元素,如何解决这个问题?
- C++ - 创建 2D 复制构造函数
- 我正在考虑为"A"类创建复制构造函数,但我不确定采用哪种方法
- 无法将类构造函数中新创建的对象复制到 C++ 中的向量成员
- 如何禁用在工厂方法之外创建/复制 obj?
- 复制文件时是否可以自动创建不存在的目录?
- Windows Portable设备 - 创建 /复制 /删除新文件时通知
- 创建一个 const unique_ptr然后尝试从它 std::move 会给出与您尝试访问复制构造函数相同的错误
- 如何从指向多态基类的指针复制/创建派生类实例