2012-05-01 63 views
2

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

#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; 
} 

输出:

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

什么是ouptput? –

+0

你可以告诉它警告你。该标志是-Wreorder,它是用-Wall打开的。 –

+1

你应该确保你用'-Wall -Werror -Wextra -pedantic-errors'进行编译。代码不会编译因为gcc会警告你你正在使用未初始化的 – inf

回答

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)

+0

我认为你是对的。正如你所提到的,从技术上讲,它与初始化顺序无关。 –

相关问题