C ++:成员类的初始化顺序 [英] C++: Initialization Order for Member Classes
问题描述
在下面的代码中,当调用X的ctor时,A或B的ctor会先调用吗?它们在类的主体中放置的顺序是控制这个的吗?如果有人可以提供一个来自C ++标准的文本片段,这将是完美的。
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
{
private:
A a;
B b;
}
推荐答案
出现在类定义中 - 这是从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:
5初始化将在
下面的顺序:
5 Initialization shall proceed in the following order:
- 首先,只有
才是最具衍生价值的
类的构造函数,如下所述,virtual base
将以
顺序初始化,它们出现在深度优先
从左到右遍历
基本
类的有向无环图,其中右是在派生类
base-specifier-list中的基类
名称的出现的
顺序。
— First, and only for the constructor of the most derived class as described below, virtual base classes shall be initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where "left-to-right" is the order of appearance of the base class names in the derived class base-specifier-list.
- 然后,直接
基类必须在
声明顺序中初始化,因为它们出现在
base-specifier-不管
是mem初始化器的顺序)。
— Then, direct base classes shall be initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).
- 然后,非静态数据成员应该是
,按它们的顺序初始化$ b在类定义
中声明(再次不考虑
mem-initializers的顺序)。
— Then, nonstatic data members shall be initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).
- 最后,构造函数的主体
被执行。 [注:
声明顺序强制为
,确保base和成员子对象
以与
初始化相反的顺序被销毁。 ]
— Finally, the body of the constructor is executed. [Note: the declaration order is mandated to ensure that base and member subobjects are destroyed in the reverse order of initialization. ]
这篇关于C ++:成员类的初始化顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!