Possible Duplicate:
Member fields, order of construction
如果我的类(class)有两个这样的成员:
class A
{
int a;
int b;
A() {}
};
构造a
和b
的顺序是否未定义?
如果我使用 cl
,那么无论我以何种顺序调用构造函数,成员总是按照它们在类中声明的顺序构造。在这种情况下,它将始终是 a
然后是 b
,即使我为 A
定义了构造函数,例如:
A() : b(), a() {}
但我假设这只是特定编译器的行为。
没有。成员按照声明的顺序构造。
建议您以相同的顺序排列您的初始化列表,但您不是必须这样做。如果您不这样做,将会非常困惑,并且可能会导致难以检测的错误。
例子:
struct Foo {
int a; int b;
Foo() : b(4), a(b) { } // does not do what you think!
};
这个构造实际上是未定义的行为,因为您正在读取初始化器 a(b)
中的未初始化变量。
标准引用(C++11、12.6.2/10):
— Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).
— Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).