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

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(示例)

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(反面示例)

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

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


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

阅读更多更新文章,请关注微信公众号【面向对象思考】

发布了408 篇原创文章 · 获赞 653 · 访问量 29万+

猜你喜欢

转载自blog.csdn.net/craftsman1970/article/details/104802529