A POD struct
can be zero-initialized in C++11 as follows:
SomeStruct s{};
However, what do I do if I already have an instance of the struct and I want to re-initialize it to zeros? The following seems to work:
s = {};
Can someone point out the relevant standardese? I assume this is what is happening:
You don't have to initialise every element of a structure, but can initialise only the first one; you don't need nested {} even to initialise aggregate members of a structure. Anything in C can be initialised with = 0 ; this initialises numeric elements to zero and pointers null.
Using designated initializers, a C99 feature which allows you to name members to be initialized, structure members can be initialized in any order, and any (single) member of a union can be initialized. Designated initializers are described in detail in Designated initializers for aggregate types (C only).
Structure members can be initialized using curly braces '{}'. For example, following is a valid initialization.
What you are looking for is in [expr.ass]
A braced-init-list may appear on the right-hand side of
- an assignment to a scalar, in which case the initializer list shall have at most a single element. The meaning of
x={v}
, where T is the scalar type of the expression x, is that ofx=T{v}
. The meaning ofx={}
isx=T{}
.- an assignment to an object of class type, in which case the initializer list is passed as the argument to the assignment operator function selected by overload resolution (13.5.3, 13.3).
So your guess is correct. The compiler may (can in C++17 and above) be able to optimize things away but you can think of it as create a zero-initialized temporary and pass it to the operator=
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With