C++核心準則C.49:構造函數中應該做的是初始化而不是賦值

C.49: Prefer initialization to assignment in constructors
C.49:構造函數中應該做的是初始化而不是賦值

 

Reason(原因)

An initialization explicitly states that initialization, rather than assignment, is done and can be more elegant and efficient. Prevents "use before set" errors.

初始化明確地表明所做的是初始化而不是賦值,而且可以做得更優美,更有效率。防止“賦值之前使用”的錯誤。

 

Example, good(良好示例)

 

class A {   // Good
    string s1;
public:
    A(czstring p) : s1{p} { }    // GOOD: directly construct (and the C-string is explicitly named)
    // ...
};

 

 

Example, bad(反面示例)

 

class B {   // BAD
    string s1;
public:
    B(const char* p) { s1 = p; }   // BAD: default constructor followed by assignment
    // ...
};

class C {   // UGLY, aka very bad
    int* p;
public:
    C() { cout << *p; p = new int{10}; }   // accidental use before initialized
    // ...
};

 

 

Example, better still(更好的示例)

Instead of those const char*s we could use gsl::string_span or (in C++17) std::string_view as a more general way to present arguments to a function:

相對於那些const char* s,我們應該可以使用gsl::string_span或者(C++17引入的)std::string_view作爲表達函數參數怒的更加普遍的方式(https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rstr-view)。

 

class D {   // Good
    string s1;
public:
    A(string_view v) : s1{v} { }    // GOOD: directly construct
    // ...
};

 

原文鏈接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c49-prefer-initialization-to-assignment-in-constructors

 


 

覺得本文有幫助?歡迎點贊並分享給更多的人。

閱讀更多更新文章,請關注微信公衆號【面向對象思考】

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章