01.15 編譯器能做的事就讓編譯器去做

編譯器能做的事就讓編譯器去做

黃鐵礦晶簇

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

<code>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;};/<code>

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

<code>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; }};/<code>

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

(中等)實現和編譯器生成版本相同的可訪問性和語義的特殊函數是多餘的工作。


覺得本文有幫助?請分享給更多人。

更多精彩文章請關注微信公眾號【面向對象思考】!

面向對象開發,面向對象思考!


分享到:


相關文章: