我有代码:
struct A { int a; }; struct B { int b; const A a[2]; }; struct C { int c; const B b[2]; }; const C test = {0,{}}; int main() { return test.c; }
我有gcc 4.8.2和4.9.2.它可以编译得很好:
g++-4.9 -Wall test.cpp -o test g++-4.8 -std=c++11 -Wall test.cpp -o test g++-4.8 -Wall test.cpp -o test
但是,它无法编译:
g++-4.9 -std=c++11 -Wall test.cpp -o test
编译器的输出是:
test.cpp:15:22: error: uninitialized const member ‘B::a’ const C test = {0,{}}; ^ test.cpp:15:22: error: uninitialized const member ‘B::a’
这是一个bug还是我只是不明白什么?
解决方法
这是一个基本上减少到GCC抱怨聚合初始化中未显式初始化的const数据成员的错误.例如.
struct {const int i;} bar = {};
Fails,因为我在bar的初始化程序中没有initializer子句.但是,该标准在§8.5.1/ 7中规定
If there are fewer initializer-clauses in the list than there are
members in the aggregate,then each member not explicitly initialized
shall be initialized from its brace-or-equal-initializer or,if there
is no brace-or-equal-initializer,from an empty initializer list
(8.5.4).
因此,代码初始化i(好像通过= {}),GCC的投诉是不正确的.
事实上,这个bug已经在四年前被报道为#49132,并在GCC 5中得到修正.