C++核心準(zhǔn)則C.49:構(gòu)造函數(shù)中應(yīng)該做的是初始化而不是賦值

C.49:構(gòu)造函數(shù)中應(yīng)該做的是初始化而不是賦值
An initialization explicitly states that initialization, rather than assignment, is done and can be more elegant and efficient. Prevents "use before set" errors.
初始化明確地表明所做的是初始化而不是賦值,而且可以做得更優(yōu)美,更有效率。防止“賦值之前使用”的錯(cuò)誤。
class A { ? // Good
? ?string s1;
public:
? ?A(czstring p) : s1{p} { } ? ?// GOOD: directly construct (and the C-string is explicitly named)
? ?// ...
};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
? ?// ...
};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:
相對(duì)于那些const char* s,我們應(yīng)該可以使用gsl::string_span或者(C++17引入的)std::string_view作為表達(dá)函數(shù)參數(shù)怒的更加普遍的方式(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
覺得本文有幫助?請(qǐng)分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
