c++ - 是否保证默认构造函数将内置类型自动初始化为 0?

标签 c++ c++11 initialization language-lawyer default-constructor

在您开始将其标记为重复之前,我已经阅读了 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,当它们是 classstruct 时 成员。 C++11 标准保证这种行为吗?

最佳答案

这个问题内置了两个独立的问题。

  1. = 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() { },它将默认初始化 sm,将它们设置为某个不确定的值。

  2. t.st.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.st.m 保证为 0,即使我们默认构造了一个本地 Test,它们也不会是。

关于c++ - 是否保证默认构造函数将内置类型自动初始化为 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33441087/

相关文章:

c++ - 为什么 std::is_array 对 std::array 返回 false?

java - 如何在 Java 7 中使用一组众所周知的值初始化无符号字节数组?

swift - 初始化不带选项的模型对象

将整数或 double 加在一起时的 C++ 奇怪输出

c++ - 为 DirectX9 使用 C++ 代理 dll,如何旋转场景?

c++ - 为什么要调用复制构造函数?

c++ - 这段代码在 ISO C++ 中合法吗?

c++ - 如何让 PCRE 与 C++ 一起工作?

c++ - 函数参数的decltype

c++ - flatbuffers schema 字段中标记的 'hash' 有什么用?