gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:57:57 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com