成员初始化列表的顺序 [英] Order of member initialization list
问题描述
在多次简化我的代码之后,我发现导致问题的原因如下.
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);
}
警告(clang 8.0.0)
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编译程序.运行该程序会导致分段错误.
g++-6 compiles the program. Running the program causes segmentation fault.
类成员的初始化是否遵循成员初始化列表(: _b(b), _b2(_b._x)
)的顺序或类中成员的顺序(如B _b2; const B& _b;
)?
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;
) ?
推荐答案
成员变量的初始化按照在类中声明它们的顺序进行.
Initialization of member variables occurs in the order that they are declared in the class.
http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-order
和:
http://en.cppreference.com/w/cpp/language/initializer_list
3)然后,按以下顺序初始化非静态数据成员 类定义中的声明.
3) Then, non-static data members are initialized in order of declaration in the class definition.
这篇关于成员初始化列表的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!