为什么 VS2013 不零初始化这个结构?

Why doesn't VS2013 zero-initialize this struct?

使用 Microsoft Visual Studio Ultimate 2013 update 4 和以下代码:

#include <iostream>

auto main() -> int {
    struct Base { int a; };
    struct Derived : Base { int b; };

    auto foo = Derived();

    std::cout << foo.a << " " << foo.b;
}

我得到这个输出:

-858993460 -858993460

但我预计:

0 0

为什么 foo 没有被零初始化?

应该初始化为零,看起来像 MSVC bug。 因为实际上你的代码是这样的

Derived foo{Derived()};

然后 copy/move 构造函数将在用 () 初始化的临时对象上调用。

n3376 8.5/10

An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.

n3376 8.5/7

To value-initialize an object of type T means:

if T is a (possibly cv-qualified) non-union class type without a user-provided or deleted default construc- tor, then the object is zero-initialized and, if T has a non-trivial default constructor, default-initialized;

n3376 8.5/5

To zero-initialize an object or reference of type T means:

if T is a (possibly cv-qualified) non-union class type, each non-static data member and each base-class subobject is zero-initialized and padding is initialized to zero bits;

您的结构没有构造函数,因此创建默认构造函数。

结构的默认构造函数将为每个成员调用默认构造函数。

int 的默认构造函数未对其进行初始化。所以 int 成员将包含随机数据。

向您的结构添加构造函数并初始化成员。像这样:

struct Base
{
    Base(): a(0) {}
    int a;
};