首页 > 解决方案 > Why is double brace required to initialize std::array of structs

问题描述

In C++17, why does this way of initializing std::array not work?

#include <array>
#include <string_view>

class myClass {

private:  

 struct myStruct {
        const std::string_view a;
        const int b;
        const int c;
    };

    static inline constexpr std::array<myStruct, 2> myArray = {{"", 0, 0},{"", 0, 0}};
};

I thought this style was covered by the changes in CWG 1270. However, the only way I found to make it work is to do:

   static inline constexpr std::array<myStruct, 2> myArray = {{{"", 0, 0},{"", 0, 0}}};

or

   static inline constexpr std::array<myStruct, 2> myArray = {myStruct{"", 0, 0},myStruct{"", 0, 0}};

标签: c++

解决方案


让我们用一个更简单的例子来解决这个问题:

std::array<int, 3> arr{{1,2,3}};

我们首先回顾如何std::array定义。它具有

与将 C 样式数组 T[N] 作为其唯一的非静态数据成员的结构具有相同的语义。

因此,换句话说,这std::array是一个具有单个“非静态数据成员”的对象,它是一个 C 样式的数组。基于此,我们可以得出:

  • 最外面的一组大括号服务器初始化std::array自身。

  • 最里面的一组大括号初始化这个未命名的数据成员。

换句话说,这与以下内容完全相同:

struct my_array {

    int a[3];
};

my_array arr{{1,2,3}};

这就是为什么总是使用一组双外括号来初始化 a 的实例std::array


推荐阅读