12

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

3 Answers 3

9

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.

1

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.