非静态数据成员按什么顺序初始化?
在下面的代码中,当X
的ctor被调用时,A
或B
的ctor会先被调用吗?它们在类主体中的放置顺序是否控制这一点?如果有人可以提供一段来自 C++ 标准的文本片段来讨论这个问题,那就完美了。
class A {};
class B {};
class X
{
A a;
B b;
};
In the following code, when the ctor of X
is called will the ctor of A
or B
be called first? Does the order in which they are placed in the body of the class control this? If somebody can provide a snippet of text from the C++ standard that talks about this issue, that would be perfect.
class A {};
class B {};
class X
{
A a;
B b;
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
顺序是它们在类定义中出现的顺序 - 这来自 C++ 标准的第 12.6.2 节:
The order is the order they appear in the class definition - this is from section 12.6.2 of the C++ Standard:
初始化始终按照类成员在类定义中出现的顺序进行,因此在示例中先是
a
,然后是b
。每个成员的初始化之间有一个序列点,您可以将对尚未初始化的成员的引用传递到类成员的构造函数中,但您只能在有限的方式(例如将其地址形成指针),其他用途很可能会导致未定义的行为。
类成员的销毁总是以与构造相反的顺序发生。
基类和成员的初始化顺序在 12.6.2 [class.base.init]/5 中定义。
Initialization is always in the order that the class members appear in your class definition, so in your example
a
, thenb
.There is a sequence point between the initialization of each member and you can pass a reference to a yet-to-be initialized member into the constructor of a class member but you would only be able to use it in limited ways (such as taking its address to form a pointer), other uses may well cause undefined behaviour.
Destruction of class members always happens in the reverse order of construction.
Order of initialization of bases and members is defined in 12.6.2 [class.base.init]/5.