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(示例)


class B { public:     virtual owner<B*> clone() = 0;     virtual ~B() = default;     B(const B&) = delete;     B& operator=(const B&) = delete; }; class D : public B { public:     owner<D*> clone() override;     ~D() override; };


 

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<D> while B::clone returns unique_ptr<B>. Therefore, you either need to consistently return unique_ptr<B> in all overrides, or use owner<> utility from the Guidelines Support Library.

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

 

原文链接

​https:///isocpp/CppCoreGuidelines/blob/master/#c130-for-making-deep-copies-of-polymorphic-classes-prefer-a-virtual-clone-function-instead-of-copy-constructionassignment​


 

觉得本文有帮助?欢迎点赞并分享给更多的人。

阅读更多更新文章,请关注微信公众号【面向对象思考】