c++ - 使用 {0} 初始化结构

标签 c++ initialization

我正在调试一些与此基本相同的代码:

struct Foo { int a; int b; };
struct Bar { Bar() {} Foo foo{0}; };

当我创建 Bar 的实例时,好像都是ab初始化为零。这是有保证的吗?我在哪里可以在规范中找到它?

最佳答案

根据 cppreference.com

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 member 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.


Foo没有默认成员初始值设定项( int b{0}; ),所以 b将通过带有空列表的列表初始化进行初始化,这意味着非类类型的值初始化:b = int() // = 0 .

关于c++ - 使用 {0} 初始化结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58590699/

相关文章:

通过类型实例进行 Swift 变量初始化

c - 我的全局变量不断重新定义自己

java - 声明一个变量但不初始化它会提高性能吗?

c++ - 在不循环 C++ 的情况下划分二维数组

python - 如何使用 python sdk 连接 bloomberg 终端?

c++ - 静态和动态内存分配有什么区别?

c++ - 为什么 std::runtime_error::what() 返回 const char* 而不是 std::string const&

c++ - 如何拦截我启动的 Internet Explorer 实例执行的 http 请求?

c++ - 标准容器的迭代器是 DefaultConstructible 吗?

c# - 如何在 C# 中初始化一个空数组?