sas*_*ang 2 c++ gcc initialization initializer-list
gcc应该警告成员变量的初始化顺序a和bC类吗?基本上,对象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;
}
Run Code Online (Sandbox Code Playgroud)
gcc的输出:
$ g++ -Wall -c ConsInit.cpp
$
Run Code Online (Sandbox Code Playgroud)
为了使其成为初始化问题的顺序,您需要实际尝试以错误的顺序初始化子对象:
public:
C() : a(), b(a) { cout << __func__ << endl; }
^^^ this is attempted initialization out of order
Run Code Online (Sandbox Code Playgroud)
如上所述,唯一的违规是在生命开始之前将一个引用(参数B::B(const A&))绑定到一个object(C::a),这是一个非常可疑的违规,因为a在$ 3.8 [basic.life]/$下,指针实际上是合法的. 5(并且在初始化之前仍然取消引用它将是UB)
| 归档时间: |
|
| 查看次数: |
814 次 |
| 最近记录: |