C++ initializer lists with fewer elements than the struct

有些话、适合烂在心里 提交于 2019-12-23 21:36:11

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/38840514/c-initializer-lists-with-fewer-elements-than-the-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!