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;
) ?