When I use an initializer list to create a struct, but the initializer list contains fewer elements than my struct, I see the remaining elements are initialized with zeroes.
Is this an undefined behaviour and I'm seeing zeroes because my compiler (VS2015) decided to zero the memory for me?
Or could someone point me to the documentation that explains this behaviour in C++?
This is my code:
struct Thing {
int value;
int* ptr;
};
void main() {
Thing thing { 5 };
std::cout << thing.value << " " << thing.ptr << std::endl;
}
And this is what it prints:
5 00000000
That last element is the one that got zeroed without an initializer.
This is defined behaviour. According to the rule of aggregate initialization, the remaining member ptr
will be value-initialized, i.e. zero-initialized to NULL pointer.
(emphasis mine)
If the number of initializer clauses is less than the number of members
and bases (since C++17)
or initializer list is completely empty, the remaining membersand bases (since C++17)
are initializedby their default initializers, if provided in the class definition, and otherwise (since C++14)
by empty lists, in accordance with the usual list-initialization rules (which performs value-initialization for non-class types and non-aggregate classes with default constructors, and aggregate initialization for aggregates). If a member of a reference type is one of these remaining members, the program is ill-formed.
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