C++核心准则C.47:按照成员变量声明的次序定义和初始化数据成员

共 854字,需浏览 2分钟

 ·

2020-01-02 23:25

20fcccda5541ec0e77d072596ce9f7f7.webp

C.47: Define and initialize member variables in the order of member declaration

C.47:按照成员变量声明的次序定义和初始化数据成员


Reason(原因)

To minimize confusion and errors. That is the order in which the initialization happens (independent of the order of member initializers).

最大限度降低混淆和错误。这(声明的次序,译者注)是初始化执行的顺序(和成员初始化器的顺序无关)


Example, bad(反面示例)

class Foo {
   int m1;
   int m2;
public:
   Foo(int x) :m2{x}, m1{++x} { }   // BAD: misleading initializer order
   // ...
};

Foo x(1); // surprise: x.m1 == x.m2 == 2

Enforcement(实施建议)

(Simple) A member initializer list should mention the members in the same order they are declared.

(简单)成员初始化列表应该按照成员被声明的次序处理它们。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c47-define-and-initialize-member-variables-in-the-order-of-member-declaration



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

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

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

浏览 40
点赞
评论
收藏
分享

手机扫一扫分享

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

手机扫一扫分享

分享
举报