Zero initialization instead of memset
Zero initialization via {}
is an effective means of initialization in C++,
including starting the lifetime of the first member of the union.
In practice, zero initialization can also effectively vectorize, similar to
memset
(perhaps compilers generally use it in cases of trivial structures),
and at the same time allows keeping the code cleaner.
(https://en.cppreference.com/w/cpp/language/zero_initialization)
Explanation Zero-initialization is performed in the following situations:
- For every named variable with static or thread-local(since C++11) storage duration that is not subject to constant initialization, before any other initialization.
- As part of value-initialization sequence for non-class types and for members of value-initialized class types that have no constructors, including value initialization of elements of aggregates for which no initializers are provided.
- When an array of any character type is initialized with a string literal that is too short, the remainder of the array is zero-initialized.
The effects of zero-initialization are: If T is a scalar type, the object is initialized to the value obtained by explicitly converting the integer literal 0 (zero) to T.
If T is a non-union class type:
-
all padding bits are initialized to zero bits,
-
each non-static data member is zero-initialized,
-
each non-virtual base class subobject is zero-initialized, and
-
if the object is not a base class subobject, each virtual base class subobject is zero-initialized.
If T is a union type:
-
all padding bits are initialized to zero bits, and
-
the object’s first non-static named data member is zero-initialized.
If T is array type, each element is zero-initialized. If T is reference type, nothing is done.