让我们有一个类的对象o
,它包含另一个类类型的成员子对象so
和sso
。考虑以下示例:
#include <iostream>
using namespace std;
struct SO{ SO(){ cout << "SO()" << endl; } };
struct SSO{ SSO(){ cout << "SSO()" << endl; } };
struct O
{
O(){ cout << "O()" << endl; }
SO so;
SSO sso;
};
int main()
{
O o = *(new O);
}
输出:
SO()
SSO()
O()
如第 5.3.4 节所述:
A new-expression that creates an object of type T initializes that object as follows:
— If the new-initializer is omitted, the object is default-initialized (8.5); if no initialization is performed,the object has indeterminate value.
— Otherwise, the new-initializer is interpreted according to the initialization rules of 8.5 for direct-initialization.
在特定情况下,为对象 o
执行默认初始化(即构造函数调用)。但是他的子对象呢?似乎也执行了默认初始化。但是,标准中哪里规定,如果子对象的完整对象默认初始化,则对任何子对象执行默认初始化?
最佳答案
说对象o
执行默认初始化是不正确的。在您的示例中,对象 o
是复制初始化的。您的示例中的默认初始化是针对 new
创建的未命名对象执行的(随后会泄漏)。
现在,由 new
创建的 O
类型的未命名对象确实是默认初始化的,在这种情况下意味着它是通过调用用户定义的默认值来初始化的构造函数O::O()
。 O::O()
构造函数中的构造函数初始值设定项列表完全不存在,即未提及任何子对象。这意味着这些子对象将被默认初始化。
如中所述
12.6.2 初始化基地和成员
8 In a non-delegating constructor, if a given non-static data member or base class is not designated by a mem-initializer-id (including the case where there is no mem-initializer-list because the constructor has no ctor-initializer) and the entity is not a virtual base class of an abstract class (10.4), then
— if the entity is a non-static data member that has a brace-or-equal-initializer, the entity is initialized as specified in 8.5;
— otherwise, if the entity is a variant member (9.5), no initialization is performed;
— otherwise, the entity is default-initialized (8.5).
最后一个选项适用于您的情况。 (由于我使用的是文档的草稿版本,因此编号可能不正确。)
请注意,您的问题标题提到了“子对象初始化顺序”,而实际问题与顺序本身无关。是关于初始化的方法。
关于c++ - 子对象初始化的顺序是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25278066/