gcc 4.9 结构初始化错误?

gcc 4.9 bug in structures initialization?

我有代码:

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’

这是一个错误还是我不明白什么?

这是一个错误,本质上减少了 GCC 抱怨聚合初始化中未明确初始化的 const 数据成员。例如

struct {const int i;} bar = {};

Fails 因为在 bar 的初始化器中没有 i 的初始化子句。但是,标准在 §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 的投诉是不正确的。

事实上,这个错误已经在四年前被报告为 #49132,并在 GCC 5 中得到修复。