多态类复制时应该使用克隆

多态类复制时应该使用克隆

C.130: For making deep copies of polymorphic classes prefer a virtual clone function instead of copy construction/assignment

C.130:实现多态类的深拷贝时,虚clone函数要比拷贝构造函数/赋值运算符好。

Reason(原因)

Copying a polymorphic class is discouraged due to the slicing problem, see C.67. If you really need copy semantics, copy deeply: Provide a virtual clone function that will copy the actual most-derived type and return an owning pointer to the new object, and then in derived classes return the derived type (use a covariant return type).

由于会发生切片问题,多态类的复制是不推荐的。如果你真的需要复制语义,就进行深拷贝:提供一个虚的克隆函数,这个函数可以复制实际的派生类型并返回一个指向新对象的所有权指针,同时在派生类中返回派生类型(使用共变量返回类型)

切片问题(slicing problerm):由派生类实例向基类实例赋值时发生的信息丢失。

​共变量返回类型(covariant return type):当基类的虚函数被派生类覆盖时,如果基类的虚函数返回某个类,而派生类返回该类的派生类,也看做是成功的覆盖。

Example(示例)

<code>classB{public:       virtualownerclone()=0;       virtual~B()=default;       B(constB&)=delete;       B&operator=(constB&)=delete;};classD:publicB{      public:owner 
clone()override; ~D()override;};
/<code>

Generally, it is recommended to use smart pointers to represent ownership (see R.20). However, because of language rules, the covariant return type cannot be a smart pointer: D::clone can't return a unique_ptr while B::clone returns unique_ptr. Therefore, you either need to consistently return unique_ptr in all overrides, or use owner<> utility from the Guidelines Support Library.

一般情况下,推荐使用智能指针表现所有权(参见R.20)。但是因为语言规则,共变量返回类型不能是智能指针:当B::clone返回unique_ptr时,D::clone不能返回unique_ptr。因此,你要么在所有的覆盖都返回unique_ptr,要么使用准则支持库中的onwer<>。

原文链接https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c130-for-making-deep-copies-of-polymorphic-classes-prefer-a-virtual-clone-function-instead-of-copy-constructionassignment


觉得本文有帮助?请分享给更多人。

更多精彩文章请关注微信公众号【面向对象思考】!

面向对象开发,面向对象思考!


分享到:


相關文章: