C++核心准则C.45:使用类内初始化器初始化数据成员
C.45: Don't define a default constructor that only initializes data members; use in-class member initializers instead
C.45:不要只初始化数据成员的默认构造函数;使用类内成员初始化器
Using in-class member initializers lets the compiler generate the function for you. The compiler-generated function can be more efficient.
使用类内初始化器可以让编译器为你生成一个函数。编译器生成的函数效率更高。
class X1 { // BAD: doesn't use member initializers
string s;
int i;
public:
X1() :s{"default"}, i{1} { }
// ...
};
class X2 {
string s = "default";
int i = 1;
public:
// use compiler-generated default constructor
// ...
};
(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
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!
评论