std::array 的内联初始化有什么问题?

What#39;s wrong with this inline initialization of std::array?(std::array 的内联初始化有什么问题?)
本文介绍了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:

在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 的内联初始化有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)