gcc 是否应该警告 C 类中成员变量 a
和 b
的初始化顺序?基本上对象 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
$
最佳答案
为了使其成为初始化顺序问题,您需要实际尝试以错误的顺序初始化子对象:
public:
C() : a(), b(a) { cout << __func__ << endl; }
^^^ this is attempted initialization out of order
如所写,唯一的违规行为是在之前将引用(B::B(const A&)
的参数)绑定(bind)到对象 (C::a
)它的生命周期开始了,这是一个非常值得怀疑的违规行为,因为在 $3.8[basic.life]/5 以下,将指针指向 a
实际上是合法的(并且在 a 的初始化之前取消引用它是 UB)
关于c++ - gcc:缺少有关构造函数中初始化顺序的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10404889/