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