c++ - 数组初始化结构

标签 c++ constructor c++14 initializer-list

我有以下数据结构

struct single_t
{
    uint16_t i1 = 0;
    uint8_t i2 = 0;
    uint8_t i3 = 0;
};

struct mapping_t
{
    uint8_t n1;
    uint8_t n2;
    bool enable;
    uint n3;
    std::array<single_t, 32> map;
};

我想用以下方式初始化它们:

mapping_t m1 {
    3,                                  // n1
    254,                                // n2
    true,                               // enable
    5,                                  // n3

    // map
    // i1                   i2              i3
    {{
        {0x1000,            1,              8}
    }}
};

我能确定 std::array<single_t, 32> map; 中的元素吗? ,在本例中索引 1..31,被初始化为 0 或者它是否像堆栈上的未初始化变量 int i; ?我的调试器显示它们为 0,但该实现是依赖于调试版本还是在标准中定义?

最佳答案

来自 http://en.cppreference.com/w/cpp/language/aggregate_initialization

If the number of initializer clauses is less than the number of members or initializer list is completely empty, the remaining members are value-initialized. If a member of a reference type is one of these remaining members, the program is ill-formed.

值初始化的默认情况是用0初始化

参见 http://en.cppreference.com/w/cpp/language/value_initialization

The effects of value initialization are:

[...]

4) otherwise, the object is zero-initialized.

总而言之,你很好!

关于c++ - 数组初始化结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42453497/

相关文章:

java - 为什么在调用构造函数时将 int 隐式转换为 float 而不是 double?

python - 如何在 Python 中调用 super 构造函数?

c++ - 在 C++(98、11 和 14)中初始化静态数据成员的正确方法是什么

c++ - 如何特化模板

C++11 非静态成员初始值设定项和已删除的复制构造函数

c++ - 关于返回对象地址的困惑

c++ - 如何检查类型是否为 int 的 typedef

c++ - 包装接收纯右值的函数时省略复制/移动

c++ - 使用 libxml++ 将处理指令添加到现有 XML 文档

c++ - 如何接受通用迭代器?