有什么不对的std ::阵列的该行内初始化? [英] What's wrong with this inline initialization of std::array?
问题描述
考虑以下声明:
的#include<阵列GT;结构点¯x
{
//的std ::阵列<布尔,3> ARR = {假的,假的,假};
布尔BRR [3] = {假的,假的,假};
};
由于是,它通常是由G ++编译5.2。但是,如果我取消注释的std ::阵列
,我得到一个错误:
TEST.CPP:5:46:错误:数组必须用括号括起来的初始化程序初始化
的std ::阵列<布尔,3> ARR = {假的,假的,假};
^
TEST.CPP:5:46:错误:太多的初始化器'的std ::阵列<布尔,3U>'
OTOH,这个声明没有作品里面问题的main()
。此外,下面的初始化不结构X
里面的工作:
的std ::阵列<布尔,3> ARR = {{假的,假的,假}};
为什么我不能用单括号括起来的简单的初始化结构中定义的?
这看起来像一个gcc的bug,请参阅:的错误65815 - 撑省音不NSDMI 工作。报告说:
在975页的C ++程序设计语言,第4版,比亚
斯特劳斯说:
数组可以通过初始化列表来初始化:阵列A1 =
{1,2,3};
和锵(V 3.5)接受它。然而,G ++ 4.9.2认为这是一个
错误:错误:数组必须用括号括起来的初始化程序初始化
常量的std ::阵列<双,3> _ar0val = {1.0,-1.0,1.0};
块引用>问题被缩小到下面的测试用例:
结构数组{
int数据[2];
};结构X {
阵列的= {1,2};
};它看起来像固定在头部的修订,在修订版本的OPS code ++工程,在现场观看。
作为使用内部的大括号的bug报告指出是一个可能的解决方法:
的std ::阵列<布尔,3> ARR = {{假的,假的,假}};
^^Consider the following declaration:
#include <array> struct X { //std::array<bool,3> arr={false,false,false}; bool brr[3]={false,false,false}; };
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, this declaration works without problems inside
main()
. Also, the following initialization does work insidestruct X
:std::array<bool,3> arr={{false,false,false}};
Why can't I use the simple initialization with single braces in struct definition?
解决方案This looks like a gcc bug see: Bug 65815 - brace elision doesn't work in NSDMI. The report says:
On Page 975 of "The C++ Programming Language", 4th edition, Bjarne Stroustrup says:
"An array can be initialized by an initializer list: array a1 = { 1, 2, 3 };"
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 }; };
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 ::阵列的该行内初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!