在下面的代码片段中,d1 的初始化器传递给尚未构造的 d2(正确吗?),所以 D 的复制构造函数中的 d.j 是未初始化的内存访问吗?
struct D
{
int j;
D(const D& d) { j = d.j; }
D(int i) { j = i; }
};
struct A
{
D d1, d2;
A() : d2(2), d1(d2) {}
};
C++ 标准的哪一部分讨论了数据成员的初始化顺序?
最佳答案
我现在手边没有标准,所以我不能引用该部分,但是结构或类成员初始化总是按照声明的顺序进行。构造函数初始化列表中提及成员的顺序无关紧要。
Gcc 有一个警告 -Wreorder
当顺序不同时发出警告:
-Wreorder (C++ only) Warn when the order of member initializers given in the code does not match the order in which they must be executed. For instance: struct A { int i; int j; A(): j (0), i (1) { } }; The compiler will rearrange the member initializers for i and j to match the declaration order of the members, emitting a warning to that effect. This warning is enabled by -Wall.
关于c++ - 标准保证初始化顺序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1774187/