首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则C.130:实现多态类的深拷贝时,虚clone函数要比拷贝构造函数/赋值运算符好

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

作者头像
面向对象思考
发布2020-03-25 16:39:00
5800
发布2020-03-25 16:39:00
举报

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://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


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

关注【面向对象思考】轻松学习每一天!

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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-02-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档