在 struct nested union/array 成员默认初始化编译,但没有正确发生?

In struct nested union/array member default initialization compiles, but is not happening correctly?

我正在尝试在以下结构中使用嵌套联合和数组在结构声明中初始化数组成员:

struct Nested
{

  union 
  {  
    short sArray[5] = {42};
    float fVal;  // Must NOT be initialized - obviously, only 1 member of a union can be
  };

  double dArray[5] = {77.7};

};

虽然代码编译得很好,但只有两个数组的第一个元素被初始化,当 running/debugging 代码..

sArray[0]设置为42,其余元素全部设置为0 dArray[0]设置为77.69999,其余全部设置为0

我找到的所有其他答案都在实例声明中提到初始化,但在 struct/class 声明中没有提到默认初始化。 我没有 seen/found gnu c++17 是否启用了此语法(也适用于数组成员)。 然而,由于它编译 WO 警告,人们会认为它应该正确。 我做错了什么吗?

编辑: 或者我如何简单地初始化我的数组?

你正在做的是aggregate initialization, which means the elements in sArray and dArray are value initialized when not specified. Because short and double are scalar types, this means zero initialization

由于除了第一个元素没有指定任何内容,所有剩余元素都将初始化为 0

根据评论中的要求,初始化数组的方法是 std::fillstd::fill_n:

#include <algorithm>

struct Nested {
    explicit Nested() {
        std::fill_n(sArray, 5, 0);
        std::fill_n(dArray, 5, 0.0);
    }
    union {
        short sArray[5];
        float fVal;  // Must NOT be initialized - obviously, only 1 member of a
                    // union can be
    };

    double dArray[5];
};

一般来说,我建议改用 std::array 及其 fill 函数:

#include <array>

struct Nested {
    explicit Nested() {
        sArray.fill(0);
        dArray.fill(0.0);
    }
    union {
        std::array<short, 5> sArray;
        float fVal;  // Must NOT be initialized - obviously, only 1 member of a
                    // union can be
    };

    std::array<double, 5> dArray;
};