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

网友投稿 556 2022-11-12

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

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

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 clone() = 0;     virtual ~B() = default;     B(const B&) = delete;     B& operator=(const B&) = delete; }; class D : public B { public:     owner 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 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​​

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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:linux下apache+SVN搭建完美版
下一篇:C++核心准则C.133:避免保护型数据成员‍
相关文章

 发表评论

暂时没有评论,来抢沙发吧~