结构变量成员后的大括号是什么意思?
What do curly braces after a struct variable member mean?
在一些维护(Valgrind'ing)期间,我遇到了这段代码:
#pragma pack(push, 1)
struct somename
{
uint16_t a{};
uint16_t b{};
uint32_t c{};
};
#pragma pack(pop)
我希望 {}
告诉编译器始终将值初始化为 0(当使用 new 进行分配或使用堆栈变量时),但我找不到任何相关示例或文档。我的这个假设是否正确?如果不是:
struct成员变量后面的大括号{}
是什么意思?
这是 default member initializer(C++11 起)。
(强调我的)
Through a default member initializer, which is a brace or equals initializer included in the member declaration and is used if the member is omitted from the member initializer list of a constructor.
If a member has a default member initializer and also appears in the member initialization list in a constructor, the default member initializer is ignored for that constructor.
因此,数据成员 a
、b
和 c
对于内置类型是 value-initialized (zero-initialized)到 0
。
如文档所述,它是零初始化here(第二种情况):
因此所有值都设置为 0。
来自docs:
Value initialization is performed when a named variable (automatic, static, or thread-local) is declared with the initializer consisting of a pair of braces T{}
.
值初始化的效果是对象被零初始化。
在一些维护(Valgrind'ing)期间,我遇到了这段代码:
#pragma pack(push, 1)
struct somename
{
uint16_t a{};
uint16_t b{};
uint32_t c{};
};
#pragma pack(pop)
我希望 {}
告诉编译器始终将值初始化为 0(当使用 new 进行分配或使用堆栈变量时),但我找不到任何相关示例或文档。我的这个假设是否正确?如果不是:
struct成员变量后面的大括号{}
是什么意思?
这是 default member initializer(C++11 起)。
(强调我的)
Through a default member initializer, which is a brace or equals initializer included in the member declaration and is used if the member is omitted from the member initializer list of a constructor.
If a member has a default member initializer and also appears in the member initialization list in a constructor, the default member initializer is ignored for that constructor.
因此,数据成员 a
、b
和 c
对于内置类型是 value-initialized (zero-initialized)到 0
。
如文档所述,它是零初始化here(第二种情况):
因此所有值都设置为 0。
来自docs:
Value initialization is performed when a named variable (automatic, static, or thread-local) is declared with the initializer consisting of a pair of braces
T{}
.
值初始化的效果是对象被零初始化。