当我使用初始化列表创建结构时,但初始化列表包含的元素少于我的结构,我看到剩余的元素被初始化为零。
这是未定义的行为吗?我看到零是因为我的编译器 (VS2015) 决定为我将内存归零吗?
或者有人可以指点我解释 C++ 中这种行为的文档吗?
这是我的代码:
struct Thing {
int value;
int* ptr;
};
void main() {
Thing thing { 5 };
std::cout << thing.value << " " << thing.ptr << std::endl;
}
这是它打印的内容:
5 00000000
最后一个元素是在没有初始化器的情况下被置零的元素。
最佳答案
这是定义的行为。根据aggregate initialization的规则,其余成员 ptr
将为 value-initialized ,即 zero-initialized到 NULL 指针。
(强调我的)
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.
关于元素少于结构的 C++ 初始值设定项列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38840514/