gpt4 book ai didi

c++ - 类组件的初始化顺序

转载 作者:可可西里 更新时间:2023-11-01 15:02:48 25 4
gpt4 key购买 nike

class D: A
{
B obj;
C obj2;
}

保证这里的构建顺序是什么?

我知道 D 将在 A、B 和 C 之后构造,但我真正想知道的是 A 是否保证在 B 或 C 之前构造,甚至 B 是否保证 em>保证在C之前构造。

我知道你可以有一个显式的初始化列表:

D(): A(), B(), C()
{}

但是初始化列表是否决定了初始化的顺序

此外,是否有任何组件有或没有默认构造函数?

最佳答案

来自 C++03 标准 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. ]

所以在这种情况下,可以保证初始化顺序首先是基类A,然后是子对象B(因为它首先出现在列表中类定义中的类成员),然后是子对象 C。初始化列表的顺序是无关紧要的,任何成员是否有默认构造函数也是如此——如果一个成员没有默认构造函数并且它没有在初始化列表中显式初始化,那么它有一个未指定的值。

关于c++ - 类组件的初始化顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6515042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com