C.45: Don't define a default constructor that only initializes data members; use in-class member initializers instead
C.45:不要隻初始化資料成員的預設構造函數;使用類内成員初始化器
Reason(原因)
Using in-class member initializers lets the compiler generate the function for you. The compiler-generated function can be more efficient.
使用類内初始化器可以讓編譯器為你生成一個函數。編譯器生成的函數效率更高。
Example, bad(反面示例)
class X1 { // BAD: doesn't use member initializers
string s;
int i;
public:
X1() :s{"default"}, i{1} { }
// ...
};
Example(示例)
class X2 {
string s = "default";
int i = 1;
public:
// use compiler-generated default constructor
// ...
};
Enforcement(實施建議)
(Simple) A default constructor should do more than just initialize member variables with constants.
(簡單)預設構造函數應該比使用常量初始化資料成員做的更多。
譯者注:差不多就是殺雞焉用牛刀的意思。
原文連結
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c45-dont-define-a-default-constructor-that-only-initializes-data-members-use-in-class-member-initializers-instead