What do curly braces after a struct variable member mean?

不打扰是莪最后的温柔 提交于 2021-01-27 10:09:52

问题


During some maintenance (Valgrind'ing) I came across this code:

#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. Am I correct in this assumption? If not:

What do the curly braces {} after a struct member variable mean?


回答1:


This is default member initializer (since 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 are value-initialized (zero-initialized for built-in types) to 0.




回答2:


It is zero initialization as documented here (second case):

So all values are set to be 0.




回答3:


From the 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{}.

The effect of value initialization is that the object is zero-initialized.



来源:https://stackoverflow.com/questions/61520931/what-do-curly-braces-after-a-struct-variable-member-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!