Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

c++ - What's wrong with this inline initialization of std::array?

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 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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} };
                         ^                 ^

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...