类组件初始化顺序 [英] Class component order of initialisation
问题描述
D类:A
{
B obj;
C obj2;
}
这里的构造顺序是什么? / p>
我知道D将在A,B和C之后构造,但我真正想知道的是A是否被保证
我知道你可以有一个明确的初始化列表:
/ p> D():A(),B(),C()
{}
但是该初始化列表是否确定初始化的顺序
?此外,是否任何组件有或没有默认构造函数?
从C ++ 03标准ISO / IEC 14882:2003(E)§12.6.2/ 5 [class.base.init]:
初始化将按照以下顺序进行:
- 首先,只有最大派生类的构造函数如下所述,虚拟基类才会按照它们出现在深度 - 首先从左到右遍历基类的有向无环图,其中从左到右是派生类中的基类类名的出现顺序 base-specifier-list 。
- 然后,直接基类应按照声明顺序初始化,因为它们出现在 base-specifier-list 中(不管 mem- )。
- 然后,非静态数据成员将按照它们在类定义中声明的顺序进行初始化(同样不考虑 mem-initializers )。
- 最后,构造函数的主体被执行。
[注意:声明顺序是强制的,以确保base和成员子对象以与初始化的相反顺序被破坏。 ]
因此,在这种情况下,您可以保证初始化的顺序将首先是基类 A
,那么子对象 B
(因为它首先出现在类定义中的类成员列表中),那么子对象 C
。初始化器列表的顺序是无关紧要的,无论任何成员是否具有默认构造函数 - 如果成员没有默认构造函数,并且没有在初始化器列表中显式初始化,那么它具有一个未指定的值。
class D: A
{
B obj;
C obj2;
}
What order of construction here is guaranteed?
I know that D will be constructed after A, B and C, but what I really want to know is whether A is guaranteed to be constructed before B or C, or even whether B is guaranteed to be constructed before C.
I know you can have an explicit initialiser list:
D(): A(), B(), C()
{}
but does that initialiser list determine the order of initialisation?
Also, does whether or not any of the components do or don't have a default constructor?
From the C++03 standard ISO/IEC 14882:2003(E) §12.6.2/5 [class.base.init]:
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. ]
So in this case, you are guaranteed that the order of initialization will be first the base class A
, then the subobject B
(since it appears first in the list of class members in the class definition), then the subobject C
. The order of the initializer list is irrelevant, as is whether or not any of the members do or do not have a default constructor—if a member does not have a default constructor and it is not explicitly initialized in an initializer list, then it has an unspecified value.
这篇关于类组件初始化顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!