Aggregate initialization initializes the data members of an aggrete class object, whereas value initialization of an aggregate will first zero initialize it which also zeroes out padding bytes, as shown by the following spec quote
if T is a (possibly cv-qualified) non-union class type, each non-static data member and each base-class subobject is zero-initialized and padding is initialized to zero bits;
Does this mean that generally one should avoid initializing aggregate structs using ()
and prefer {}
instead because the latter doesn't have to ensure that padding bits are zero?
If the answer to the above is "no", are there cases where implementations don't fill padding with {}
but do with ()
? And among these cases, what is the better choice to use for the programmer?
(since C++20) Otherwise, if the initializer list is non-empty, the explicitly initialized elements of the aggregate are the first n elements of the aggregate, where n is the number of elements in the initializer list. Otherwise, the initializer list must be empty ({}), and there are no explicitly initialized elements.
Zero Initialization in C++Setting the initial value of an object to zero is called the zero initialization.
Formal definition from the C++ standard (C++03 8.5. 1 §1): An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual functions (10.3).
An aggregate class gives users direct access to its members and has special initialization syntax. A class is an aggregate if. • All of its data members are public. • It does not define any constructors. • It has no in-class initializers (§ 2.6.1, p.
No. Firstly, I suspect that most compilers will actually value initialize an aggregate (given constant arguments) with a single value (including padding) anyway.
However the important reason why not, is that this sort of micro-optimization should be left until you have measurements which show there is a problem (and I bet you will never get those measurements). In the meantime, write whichever is the clearest.
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