简体   繁体   English

结构变量成员后的花括号是什么意思?

[英]What do curly braces after a struct variable member mean?

During some maintenance (Valgrind'ing) I came across this code:在一些维护(Valgrind'ing)期间,我遇到了这段代码:

#pragma pack(push, 1)
struct somename
{
  uint16_t a{};
  uint16_t b{};
  uint32_t  c{};
};
#pragma pack(pop)

I would expect that the {} tell the compiler to always initialize the values to 0 (when allocating using new, or using a stack variable), but I cannot find any examples or documentation on that.我希望{}告诉编译器始终将值初始化为 0(使用 new 或使用堆栈变量进行分配时),但我找不到任何示例或文档。 Am I correct in this assumption?我在这个假设中正确吗? If not:如果不:

What do the curly braces {} after a struct member variable mean?结构成员变量后的花括号{}是什么意思?

This is default member initializer (since C++11).这是默认成员初始值设定项(C++11 起)。

(emphasis mine) (强调我的)

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.如果成员具有默认成员初始化程序并且还出现在构造函数的成员初始化列表中,则该构造函数的默认成员初始化程序将被忽略。

As the effect, the data members a , b and c arevalue-initialized ( zero-initialized for built-in types) to 0 .结果,数据成员abc初始化值(内置类型 为零初始化)为0

It is zero initialization as documented here (second case):这是 此处记录的零初始化(第二种情况):

So all values are set to be 0.所以所有值都设置为0。

From thedocs :文档

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{} .当使用由一对大括号T{}组成的初始化程序声明命名变量(自动、static 或线程本地)时,将执行值初始化。

The effect of value initialization is that the object is zero-initialized.值初始化的效果是object被零初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM