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

面向对象思考

共 404字,需浏览 1分钟

 ·

2020-01-16 23:22

9c64cbf90a06ca3c7797c46367725360.webp

黄铁矿晶簇

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

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

313ff652aa9cdff1f54322de7d6c097c.webpReason(原因)

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

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


313ff652aa9cdff1f54322de7d6c097c.webpExample(示例)
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是达到相同效果的最好、最简单的方式。


313ff652aa9cdff1f54322de7d6c097c.webpExample, bad(反面示例)
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.

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


313ff652aa9cdff1f54322de7d6c097c.webpEnforcement(实施建议)
(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

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




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

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

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



浏览 24
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报