C++核心准则C.45:使用类内初始化器初始化数据成员

共 1050字,需浏览 3分钟

 ·

2019-12-31 23:23

1e37e9894706269dcba781ff6ea5679e.webp

C.45: Don't define a default constructor that  only initializes data members; use in-class member initializers instead

C.45:不要只初始化数据成员的默认构造函数;使用类内成员初始化器


1e742695fdb54eb5a3ee5db6a50797f8.webpReason(原因)

Using in-class member initializers lets the compiler generate the function for you. The compiler-generated function can be more efficient.

使用类内初始化器可以让编译器为你生成一个函数。编译器生成的函数效率更高。


1e742695fdb54eb5a3ee5db6a50797f8.webpExample, bad(反面示例)
class X1 { // BAD: doesn't use member initializers
   string s;
   int i;
public:
   X1() :s{"default"}, i{1} { }
   // ...
};

1e742695fdb54eb5a3ee5db6a50797f8.webpExample(示例)
class X2 {
   string s = "default";
   int i = 1;
public:
   // use compiler-generated default constructor
   // ...
};

1e742695fdb54eb5a3ee5db6a50797f8.webpEnforcement(实施建议)

(Simple) A default constructor should do more than just initialize member variables with constants.

(简单)默认构造函数应该比使用常量初始化数据成员做的更多。

cb7911aa226f3c3ab7cde10dfe6c7412.webp译者注:差不多就是杀鸡焉用牛刀的意思。bd1b465a151b9fe063b02cc4660ea174.webp


1e742695fdb54eb5a3ee5db6a50797f8.webp原文链接

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




觉得本文有帮助?请分享给更多人。

关注【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!


浏览 21
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报