标准是否保证初始化顺序? [英] Is the order of initialization guaranteed by the standard?
问题描述
在下面的代码片段中,d1的初始值设定项传递了尚未构造的d2(正确吗?),所以D的复制构造函数中的dj是未初始化的内存访问吗?
In the following code snippet d1's initializer is passed d2 which has not been constructed yet (correct?), so is the d.j in D's copy constructor an uninitialized memory access?
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 ++标准的哪一部分讨论了数据成员的初始化顺序?
Which section of C++ standard discusses order of initialization of data members?
推荐答案
我现在没有标准的方便工具,所以我无法引用该部分,但是结构或类成员的初始化总是 以声明的顺序发生。在构造函数初始化程序列表中提到成员的顺序无关。
I don't have the standard handy right now so I can't quote the section, but structure or class member initialisation always happens in declared order. The order in which members are mentioned in the constructor initialiser list is not relevant.
Gcc发出警告 -Wreorder
当顺序不同时发出警告:
Gcc has a warning -Wreorder
that warns when the order is different:
-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.
这篇关于标准是否保证初始化顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!