数组初始化结构
Array initialization with structures
我有以下数据结构
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.
总结一下,你很好!
我有以下数据结构
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.
总结一下,你很好!