Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ initializer lists with fewer elements than the struct

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.

like image 444
Daniel Avatar asked Sep 13 '25 17:09

Daniel


1 Answers

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 members and bases (since C++17) are initialized by 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.

like image 166
songyuanyao Avatar answered Sep 16 '25 08:09

songyuanyao