元素少于结构的 C++ 初始值设定项列表

标签 c++ struct initialization

当我使用初始化列表创建结构时,但初始化列表包含的元素少于我的结构,我看到剩余的元素被初始化为零。

这是未定义的行为吗?我看到零是因为我的编译器 (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 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.

关于元素少于结构的 C++ 初始值设定项列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38840514/

相关文章:

c - 指向 "typedef struct"声明的指针

c++ - 初始化一个包含 vector 的结构

c++ - 包装右值引用 lambda 时 std::async 和 std::bind 之间的区别

带有 OpenMP 线程安全随机数的 C++

WebSocket 消息中的 JavaScript 双反斜杠

c++ - 在 C++ 的类构造函数中初始化结构数组

c++ - 有没有办法用混合字符和 "strings"初始化数组

java - 如何在 Try/Catch block 之前初始化输入流

c++ - 带有 QT 错误 : ASSERT :"QOpenGLFunctions::isInitialized(d_ptr)". 的 OpenGL 无法创建 OpenGL 上下文

c++ - C++中双引号内字符串的数据类型是什么