gcc:缺乏关于构造函数初始化顺序的警告

时间:2012-05-01 21:50:47

标签: c++ gcc initialization initializer-list

gcc应该警告C类中成员变量ab的初始化顺序吗?基本上,对象b被初始化,并且在对象A之前调用它的构造函数。这意味着b使用未初始化的a

#include <iostream>

using namespace std;

class A
{
    private:
        int x;
    public:
        A() : x(10) { cout << __func__ << endl; }
        friend class B;
};

class B
{
    public:
        B(const A& a) { cout << "B: a.x = " << a.x << endl; }
};

class C
{
    private:
        //Note that because b is declared before a it is initialized before a
        //which means b's constructor is executed before a.
        B b;
        A a;

    public:
        C() : b(a) { cout << __func__ << endl; }
};

int main(int argc, char* argv[])
{
    C c;
}

gcc的输出:

$ g++ -Wall -c ConsInit.cpp 
$ 

1 个答案:

答案 0 :(得分:5)

为了使这成为初始化问题的顺序,您需要实际尝试以错误的顺序初始化子对象:

public:
    C() : a(), b(a) { cout << __func__ << endl; } 
          ^^^ this is attempted initialization out of order

如上所述,唯一的违规是在生命开始之前将引用(B::B(const A&)的参数)绑定到对象(C::a),这是一个非常可疑的违规,因为指针指向a实际上是合法的,低于$ 3.8 [basic.life] / 5(并且在初始化之前仍然取消引用它是UB)