给定代码:
struct Test {
int a = 1;
int b = 2;
};
Test test1;
Test test2{};
对于test2
,我确定test2.a == 1
和test2.b == 2
。 test1
(没有 {}
)是否保证(或不)相同?
最佳答案
线
Test test1;
等同于使用默认构造函数进行初始化,如果没有带有显式初始化列表且没有 Test() = deleted;
的手写构造函数,最终将设置两个成员为其指定的初始值 1
和 2
。
“默认构造函数”是可以不带参数调用的构造函数,这正是上述语句的情况。
您可以在 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/