问题
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