这个 std::array 的内联初始化有什么问题? [英] What's wrong with this inline initialization of std::array?

查看:47
本文介绍了这个 std::array 的内联初始化有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下声明:

#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:

The C++ Programming Language"第 975 页,第 4 版,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 的内联初始化有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆