Order of member initialization list [duplicate]

扶醉桌前 提交于 2019-12-23 05:40:06

问题


After simplifying my code for many times, I found the following cause the problem.

class B {
public:
    B(const int x)
              :_x(x) {}
    const int _x;
};

class C {
public:
    C(const B& b) 
        : _b(b), _b2(_b._x) {}
    B _b2;       // line 1
    const B& _b; // line 2
};

int main() {
    B b(1);
    C c(b);
}

Warning (clang 8.0.0)

test16.cpp:11:22: warning: reference '_b' is not yet bound to a value when used here [-Wuninitialized]
        : _b(b), _b2(_b._x) {}
                     ^
1 warning generated.

g++-6 compiles the program. Running the program causes segmentation fault.

Does the initialization of members of a class follows the order of the member initialization list (: _b(b), _b2(_b._x)) or the order of the members in the class (like B _b2; const B& _b;) ?


回答1:


Initialization of member variables occurs in the order that they are declared in the class.

http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-order

and:

http://en.cppreference.com/w/cpp/language/initializer_list

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




回答2:


The order how you specify in the member initializer list doesn't matter, non-static members are initialized in order of declaration in the class definition.

The order of member initializers in the list is irrelevant: the actual order of initialization is as follows:

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

That means _b2 will always be initialized before _b; and when _b is used to initialize _b2 it's still not initialized.

BTW: The similar rule is applied for the initializations of direct base classes.

2) Then, direct base classes are initialized in left-to-right order as they appear in this class's base-specifier list



来源:https://stackoverflow.com/questions/41886549/order-of-member-initialization-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!