简体   繁体   English

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

[英]C++ multiple access specifiers and order of initialization

We know that in the following code我们知道在下面的代码中

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

"i" is going to be init before "b". “i”将在“b”之前初始化。 If I try to init "b" before "i", I'll get a warning.如果我尝试在“i”之前初始化“b”,我会收到警告。

what about this case:这个案例怎么样:

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

?

We know that the compiler is free to order "i" and "b" since they are in separate access specifiers.我们知道编译器可以自由排序“i”和“b”,因为它们位于不同的访问说明符中。

So what is the order of initialization in this case?那么在这种情况下初始化的顺序是什么?

anything guaranteed like in the previous simple case?像前面的简单案例一样有任何保证吗?

The order of initialization is guaranteed;保证初始化顺序; i is always initialized before b . i总是在b之前初始化。 Non-static data members are initialized in the order of their declaration in the class definition, regardless of their access specifiers.非静态数据成员按其在 class 定义中声明的顺序进行初始化,而不管其访问说明符如何。

[class.base.init]/13.3 [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).然后,非静态数据成员按照它们在 class 定义中声明的顺序进行初始化(同样与内存初始化器的顺序无关)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM