问题描述
考虑以下声明:
#include <array>
struct X
{
//std::array<bool,3> arr={false,false,false};
bool brr[3]={false,false,false};
};
按原样,它可以通过 g++ 5.2 正常编译.但是如果我取消注释 std::array
,我会得到一个错误:
As is, it compiles normally by g++ 5.2. But if I uncomment the std::array
, I get an error:
test.cpp:5:46: error: array must be initialized with a brace-enclosed initializer
std::array<bool,3> arr={false,false,false};
^
test.cpp:5:46: error: too many initializers for ‘std::array<bool, 3u>’
OTOH,这个声明在 main()
中没有问题.此外,以下初始化确实在 struct X
中起作用:
OTOH, this declaration works without problems inside main()
. Also, the following initialization does work inside struct X
:
std::array<bool,3> arr={{false,false,false}};
为什么我不能在结构定义中使用带单括号的简单初始化?
Why can't I use the simple initialization with single braces in struct definition?
推荐答案
这看起来像一个 gcc 错误,请参阅:错误 65815 - 大括号省略在 NSDMI 中不起作用.报告说:
This looks like a gcc bug see: Bug 65815 - brace elision doesn't work in NSDMI. The report says:
在C++ 编程语言"第 4 版的第 975 页上,BjarneStroustrup 说:
On Page 975 of "The C++ Programming Language", 4th edition, Bjarne Stroustrup says:
"一个数组可以通过一个初始化列表来初始化:array a1 ={ 1, 2, 3 };"
"An array can be initialized by an initializer list: array a1 = { 1, 2, 3 };"
并且 Clang (V 3.5) 接受它.然而,G++ 4.9.2 认为这是一个错误:
and Clang (V 3.5) accepts it. However, G++ 4.9.2 thinks this is an error:
"error: array must be initialized with a brace-enclosed initializer
const std::array<double, 3> _ar0val = {1.0, -1.0, 1.0};"
问题被缩小到以下测试用例:
The issue was narrowed down to the following test case:
struct array {
int data [2];
};
struct X {
array a = { 1, 2 };
};
看起来修复在头部版本中,OPs 代码在该版本中有效,实时查看.
It looks like the fix is in the head revision, the OPs code works in that revision, see it live.
正如错误报告中所述,使用内部大括号是一种可能的解决方法:
As noted in the bug report using an inner set of braces is a possible work-around:
std::array<bool,3> arr={ {false,false,false} };
^ ^
这篇关于std::array 的内联初始化有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!