C++核心準(zhǔn)則C.80:如果明確希望使用默認(rèn)語義,使用=default

黃鐵礦晶簇
C.80: Use =default if you have to be explicit about using the default semantics
C.80:如果明確希望使用默認(rèn)語義,使用=default
Reason(原因)The compiler is more likely to get the default semantics right and you cannot implement these functions better than the compiler.
編譯器更有可能正確地處理默認(rèn)函數(shù)的語義,你無法比編譯器做得更好。
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.
因?yàn)槎x了析構(gòu)函數(shù),我們必須定義拷貝和移動操作。使用=default是達(dá)到相同效果的最好、最簡單的方式。
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.
實(shí)際實(shí)現(xiàn)拷貝和移動操作的工作冗長、乏味且易錯。編譯器會做得更好。
Enforcement(實(shí)施建議)(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
(中等)實(shí)現(xiàn)和編譯器生成版本相同的可訪問性和語義的特殊函數(shù)是多余的工作。
覺得本文有幫助?請分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
