Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate vs value initializing an aggregate class object with padding

Tags:

c++

padding

c++14

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?

like image 555
Johannes Schaub - litb Avatar asked Jul 18 '16 16:07

Johannes Schaub - litb


People also ask

What is aggregate initialization in C++?

(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.

What is zero initialization in c++?

Zero Initialization in C++Setting the initial value of an object to zero is called the zero initialization.

What is an aggregate type C++?

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).

What is an aggregate class?

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.


1 Answers

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.

like image 186
Martin Bonner supports Monica Avatar answered Oct 26 '22 23:10

Martin Bonner supports Monica