在您开始将其标记为重复之前,我已经阅读了 this .但它没有回答我的问题。链接的问题讨论的是 C++98 和 C++03,但我的问题是关于 C++11 引入的默认构造函数。
考虑以下程序(参见现场演示 here ):
#include <iostream>
struct Test
{
int s;
float m;
Test(int a,float b) : s(a),m(b)
{ }
Test()=default;
}t;
int main()
{
std::cout<<t.s<<'\n';
std::cout<<t.m<<'\n';
}
我的问题是编译器在这里提供的默认构造函数总是将 C++11 和 C++14 中的内置类型默认初始化为 0,当它们是 class
和 struct 时
成员。 C++11 标准保证这种行为吗?
最佳答案
这个问题内置了两个独立的问题。
= default
对默认构造函数意味着什么?来自 [class.ctor]:A default constructor that is defaulted and not defined as deleted is implicitly defined when it is odr-used (3.2) to create an object of its class type (1.8) or when it is explicitly defaulted after its first declaration. The implicitly-defined default constructor performs the set of initializations of the class that would be performed by a user-written default constructor for that class with no ctor-initializer (12.6.2) and an empty compound-statement.
也就是说,
Test() = default
完全等同于Test() { }
,它将默认初始化s
和m
,将它们设置为某个不确定的值。t.s
和t.m
是如何初始化的?是的,这是与 (1) 不同的问题,因为我们不只是在这里调用默认构造函数。来自 [basic.stc.static]:All variables which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration.
来自 [basic.start.init]:
Variables with static storage duration (3.7.1) or thread storage duration (3.7.2) shall be zero-initialized (8.5) before any other initialization takes place.
因此
t.s
和t.m
保证为 0,即使我们默认构造了一个本地Test
,它们也不会是。
关于c++ - 是否保证默认构造函数将内置类型自动初始化为 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33441087/