前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则​讨论:按照成员声明的顺序定义和初始化成员变量

C++核心准则​讨论:按照成员声明的顺序定义和初始化成员变量

作者头像
面向对象思考
发布2020-12-15 15:02:59
8120
发布2020-12-15 15:02:59
举报

Discussion: Define and initialize member variables in the order of member declaration

讨论:按照成员声明的顺序定义和初始化成员变量

Member variables are always initialized in the order they are declared in the class definition, so write them in that order in the constructor initialization list. Writing them in a different order just makes the code confusing because it won't run in the order you see, and that can make it hard to see order-dependent bugs.

成员变量总是按照它们在类定义中声明的顺序进行初始化,因此请按该顺序将其写入构造函数初始化列表中。以不同的顺序编写它们只会使代码令人困惑,因为它不会按照您看到的顺序运行,并且这使得很难看到与顺序相关的错误。

代码语言:javascript
复制
class Employee {
    string email, first, last;
public:
    Employee(const char* firstName, const char* lastName);
    // ...
};

Employee::Employee(const char* firstName, const char* lastName)
  : first(firstName),
    last(lastName),
    // BAD: first and last not yet constructed
    email(first + "." + last + "@acme.com")
{}

In this example, email will be constructed before first and last because it is declared first. That means its constructor will attempt to use first and last too soon -- not just before they are set to the desired values, but before they are constructed at all.

在此示例中,由于email对象首先被声明,所以将在first和last之前进行构造。这意味着它的构造函数试图过早使用first和last-不仅早于将它们设置为所需值之前,甚至会遭遇对象完全构造之前。

If the class definition and the constructor body are in separate files, the long-distance influence that the order of member variable declarations has over the constructor's correctness will be even harder to spot.

如果类定义和构造函数体位于不同的文件中,则成员变量声明的顺序对构造函数正确性的远程影响将更加难以发现。

References(参考):

[Cline99] §22.03-11, [Dewhurst03] §52-53, [Koenig97] §4, [Lakos96] §10.3.5, [Meyers97] §13, [Murray93] §2.1.3, [Sutter00] §47

原文链接

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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-12-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Discussion: Define and initialize member variables in the order of member declaration
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档