C++ 多重访问说明符和初始化顺序

C++ multiple access specifiers and order of initialization

我们知道在下面的代码中

class Foo1 {
private:
    int i;
    bool b;
public:
    Foo1() : i(7), b(false) {} 
};

“i”将在“b”之前初始化。如果我尝试在“i”之前初始化“b”,我会收到警告。

这个案例怎么样:

class Foo2 {
private:
    int i;
private:
    bool b;
public:
    // what happens if b is first because compiler reordered?
    Foo2() : b(false),  i(7) {} 
};

?

我们知道编译器可以自由排序“i”和“b”,因为它们位于不同的访问说明符中。

那么在这种情况下初始化的顺序是什么?

像前面的简单案例一样有任何保证吗?

保证初始化顺序; i 总是在 b 之前初始化。 Non-static 数据成员按照它们在 class 定义中声明的顺序进行初始化,而不考虑它们的访问说明符。

[class.base.init]/13.3

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).