10

我有代码:

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’

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

4

1 回答 1

3

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

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

失败i,因为in的初始化程序没有初始化子句bar。但是,该标准§8.5.1/7规定

如果列表中的初始化子句少于聚合中的成员,则每个未显式初始化的成员都应从其大括号或相等初始化器初始化,或者,如果没有大括号或相等初始化器从一个空的初始化列表 (8.5.4)

因此,代码初始化i(好像 by = {}),并且 GCC 的投诉是不正确的。

事实上,这个 bug 早在四年前就被报告为#49132,并在 GCC 5 中得到修复。

于 2015-04-07T15:50:45.167 回答