gpt4 book ai didi

c++ - gcc 4.9 结构初始化错误?

转载 作者:可可西里 更新时间:2023-11-01 16:19:05 25 4
gpt4 key购买 nike

我有代码:

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 中得到修复。

关于c++ - gcc 4.9 结构初始化错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29487390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com