brace-or-equal-initializers 初始化顺序

brace-or-equal-initializers initialization order

如果使用brace-or-equal-initializers,成员变量的初始化顺序是什么?它们的初始化与代码顺序相同吗?

struct foo {
    int x = 1;
    int y = x + 1;
} bar;

无论编译器如何,bar.y 总是 2 吗?

是的,y保证在x之后初始化。非静态数据成员总是 initialized in order of their declaration in the class definition, regardless of how they're initialized (by member initializer list or default member initializer, even default initialization).

3) Then, non-static data member are initialized in order of declaration in the class definition.

来自 Scott Meyers 的书,Effective C++,第 4 项:

One aspect of C++ that isn’t fickle is the order in which an object’s data is initialized. This order is always the same: base classes are initialized before derived classes (see also Item 12), and within a class, data members are initialized in the order in which they are declared.