c++ - POD成员默认初始化不带大括号

标签 c++ c++14 list-initialization

给定代码:

struct Test {
    int a = 1;
    int b = 2;
};

Test test1;
Test test2{};

对于test2,我确定test2.a == 1test2.b == 2test1(没有 {})是否保证(或不)相同?

最佳答案

线

Test test1;

等同于使用默认构造函数进行初始化,如果没有带有显式初始化列表且没有 Test() = deleted; 的手写构造函数,最终将设置两个成员为其指定的初始值 12

“默认构造函数”是可以不带参数调用的构造函数,这正是上述语句的情况。

您可以在 standard 中阅读默认构造函数的规则。 - 转到 § 12.1 第 4 节:

A default constructor for a class X is a constructor of class X that can be called without an argument...

在第 5 部分进一步:

A default constructor that is defaulted and not defined as deleted is implicitly defined when it is odrused (3.2) to create an object of its class type (1.8)...

关于c++ - POD成员默认初始化不带大括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43455035/

相关文章:

c++ - 实现定义的缩小转换?

c++ - 如何在类声明中初始化一个 CEvent 成员?

c++ - 使期望单个模板参数的模板模板参数的类接受可变模板参数的模板模板参数?

c++ - 为什么堆栈和堆在内存中如此分离?

c++ - 来自 std::wstring 的 Asisgn LPCWSTR 数组

c++ - 如何绘制具有随机顶点数的多边形并旋转它们?

c++ - decltype 行为背后的基本原理是什么?

c++ - 如何用基于函数的值填充 const std::array<size_t, N>

c - 在大括号和没有大括号的列表中声明的值有什么区别

c++ - Visual Studio : Avoid console from popping up and integrate it into IDE instead