C ++:类数据成员的初始化顺序

C++: Initialization Order of Class Data Members

在以下代码中,当调用X的ctor时,将首先调用AB的ctor吗? 它们在类主体中的放置顺序是否对此有所控制? 如果有人可以提供有关此问题的C ++标准的摘要,那将是完美的。

1
2
3
4
5
6
7
class A {};
class B {};
class X
{
 A a;
 B b;
};


该顺序是它们在类定义中出现的顺序-这来自C ++标准的12.6.2节:

5 Initialization shall proceed in the
following order:

— 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.

— 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).

— 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).

— 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. ]


初始化总是按照类成员出现在类定义中的顺序进行,因此在您的示例中,依次为ab

每个成员的初始化之间都有一个序列点,您可以将对尚未初始化的成员的引用传递到类成员的构造函数中,但您只能以有限的方式使用它(例如,使用它的 地址以形成一个指针),其他用途很可能导致不确定的行为。

破坏班级成员总是以相反的顺序进行。

基数和成员的初始化顺序在12.6.2 [class.base.init] / 5中定义。