【发布时间】:2015-02-09 11:40:06
【问题描述】:
我不明白 C++11 大括号初始化规则在这里是如何工作的。 拥有此代码:
struct Position_pod {
int x,y,z;
};
class Position {
public:
Position(int x=0, int y=0, int z=0):x(x),y(y),z(z){}
int x,y,z;
};
struct text_descriptor {
int id;
Position_pod pos;
const int &constNum;
};
struct text_descriptor td[3] = {
{0, {465,223}, 123},
{1, {465,262}, 123},
};
int main()
{
return 0;
}
注意,数组被声明为有 3 个元素,但只提供了 2 个初始化器。
但是它编译没有错误,这听起来很奇怪,因为最后一个数组元素的引用成员将未初始化。确实,它有 NULL 值:
(gdb) p td[2].constNum
$2 = (const int &) @0x0: <error reading variable>
现在是“魔法”:我将 Position_pod 更改为 Position
struct text_descriptor {
int id;
Position_pod pos;
const int &constNum;
};
变成这样:
struct text_descriptor {
int id;
Position pos;
const int &constNum;
};
现在它给出了预期的错误:
error: uninitialized const member ‘text_descriptor::constNum'
我的问题:为什么它在第一种情况下编译,什么时候应该给出错误(如在第二种情况下)。 不同之处在于,Position_pod 使用 C 风格的大括号初始化,而 Position 使用 C++11 风格的初始化,调用 Position 的构造函数。但这如何影响不初始化引用成员的可能性呢?
(更新) 编译器: gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2
【问题讨论】:
-
编译器版本很重要。 Clang 3.5 and GCC 4.9.2 不要编译这个。
-
看起来像一个编译器错误。我可以在 GCC 4.8 及更早版本上重现,所以看起来它已在 4.9 中修复。
-
@remyabel GCC 4.9.2 确实使用
-std=c++03编译它。 -
@PavelOganesyan:该类中有一个默认构造函数。
-
请致电语言律师。