c++ - 成员初始化列表顺序

标签 c++ initialization member-initialization

<分区>

经过多次简化我的代码后,我发现了以下导致问题的原因。

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)

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编译程序。运行程序导致段错误。

类成员的初始化是按照成员初始化列表(: _b(b), _b2(_b._x))的顺序还是类中成员的顺序(像 B _b2; const B& _b;) ?

最佳答案

成员变量的初始化按照它们在类中声明的顺序进行。

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

和:

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.

关于c++ - 成员初始化列表顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41886549/

相关文章:

c++ - 错误:使用 getline 时 basic_istream<char> 变为非标量类型 cxx11::string

c++ - 两个 std::shared_ptr 运行时错误

swift - 无法将类型 'CFTimeInterval.Type' 的值转换为 'CFTimeInterval'?

c++ - 将对象重置为初始状态的模式

c++ - 有没有一种方法可以使用c++实时阅读文本?

c++ - 代码 :Blocks Mingw Compiler Error: Variable-Sized Object May Not Be Initialized

c++ - 现在我们有了 std::array C 风格的数组还有什么用途?

c++ - 具有默认参数的成员初始化列表

c++ - 尝试在类成员初始化中使用 vector 的填充构造函数失败。怎么了?

c++ - 在 C++ 中使用 'cin' 使数组与输入一样大