前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则C.80:如果明确希望使用默认语义,使用=default

C++核心准则C.80:如果明确希望使用默认语义,使用=default

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

黄铁矿晶簇

C.80: Use =default if you have to be explicit about using the default semantics

C.80:如果明确希望使用默认语义,使用=default

Reason(原因)

The compiler is more likely to get the default semantics right and you cannot implement these functions better than the compiler.

编译器更有可能正确地处理默认函数的语义,你无法比编译器做得更好。

Example(示例)

代码语言:javascript
复制
class Tracer {
    string message;
public:
    Tracer(const string& m) : message{m} { cerr << "entering " << message << '\n'; }
    ~Tracer() { cerr << "exiting " << message << '\n'; }

    Tracer(const Tracer&) = default;
    Tracer& operator=(const Tracer&) = default;
    Tracer(Tracer&&) = default;
    Tracer& operator=(Tracer&&) = default;
};

Because we defined the destructor, we must define the copy and move operations. The = default is the best and simplest way of doing that.

因为定义了析构函数,我们必须定义拷贝和移动操作。使用=default是达到相同效果的最好、最简单的方式。

Example, bad(反面示例)

代码语言:javascript
复制
class Tracer2 {
    string message;
public:
    Tracer2(const string& m) : message{m} { cerr << "entering " << message << '\n'; }
    ~Tracer2() { cerr << "exiting " << message << '\n'; }

    Tracer2(const Tracer2& a) : message{a.message} {}
    Tracer2& operator=(const Tracer2& a) { message = a.message; return *this; }
    Tracer2(Tracer2&& a) :message{a.message} {}
    Tracer2& operator=(Tracer2&& a) { message = a.message; return *this; }
};

Writing out the bodies of the copy and move operations is verbose, tedious, and error-prone. A compiler does it better.

实际实现拷贝和移动操作的工作冗长、乏味且易错。编译器会做得更好。

Enforcement(实施建议)

(Moderate) The body of a special operation should not have the same accessibility and semantics as the compiler-generated version, because that would be redundant

(中等)实现和编译器生成版本相同的可访问性和语义的特殊函数是多余的工作。


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

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

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

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • (Moderate) The body of a special operation should not have the same accessibility and semantics as the compiler-generated version, because that would be redundant
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档