前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则C.22:保持默认操作的一贯性

C++核心准则C.22:保持默认操作的一贯性

作者头像
面向对象思考
发布2020-03-25 16:01:11
3110
发布2020-03-25 16:01:11
举报
文章被收录于专栏:C++核心准则原文翻译

C.22: Make default operations consistent

C.22: 保持默认操作的一贯性

Reason(原因)

The default operations are conceptually a matched set. Their semantics are interrelated. Users will be surprised if copy/move construction and copy/move assignment do logically different things. Users will be surprised if constructors and destructors do not provide a consistent view of resource management. Users will be surprised if copy and move don't reflect the way constructors and destructors work.

默认操作从概念上讲是配合严密的一整套处理。它们的语义是相互关联的。如果拷贝/移动构造和拷贝/移动赋值做的是逻辑上不同的事情,用户会感到诧异;如果构造函数和析构函数没有为资源管理提供一致的想法,用户会感到诧异;如果拷贝和移动操作没有对应构造函数和析构函数的动作,用户会感到诧异。

Example, bad(反面示例)
代码语言:javascript
复制
class Silly {   // BAD: Inconsistent copy operations
    class Impl {
        // ...
    };
    shared_ptr<Impl> p;
public:
    Silly(const Silly& a) : p{a.p} { *p = *a.p; }   // deep copy
    Silly& operator=(const Silly& a) { p = a.p; }   // shallow copy
    // ...
};

These operations disagree about copy semantics. This will lead to confusion and bugs.

这些操作(拷贝构造和赋值)关于拷贝的语义不同(风别是深拷贝和浅拷贝)。这会导致困惑和错误。

Enforcement(实施建议)
  • (Complex) A copy/move constructor and the corresponding copy/move assignment operator should write to the same member variables at the same level of dereference. (复杂) 拷贝/移动构造函数和对应的拷贝/移动赋值运算符应该以同样的的解引用级别写入同样的成员变量。
  • (Complex) Any member variables written in a copy/move constructor should also be initialized by all other constructors. (复杂)在拷贝/移动构造函数中写入的任何成员变量也应该被其他的构造函数初始化。
  • (Complex) If a copy/move constructor performs a deep copy of a member variable, then the destructor should modify the member variable. (复杂)如果拷贝/移动构造函数对成员变量进行深拷贝,那么析构函数应该修改该成员变量。
  • (Complex) If a destructor is modifying a member variable, that member variable should be written in any copy/move constructors or assignment operators.
  • (复杂)如果析构函数修改某个成员变量,那么这个成员变量应该在拷贝/移动构造函数或者赋值运算符中被写入。

原文链接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c22-make-default-operations-consistent


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

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

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

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • C.22: Make default operations consistent
    • Reason(原因)
      • Example, bad(反面示例)
        • Enforcement(实施建议)
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档