c++ - 值初始化与聚合初始化

标签 c++ c++11 visual-c++-2013

我遇到了值初始化与聚合初始化混合的问题。 到目前为止,我尝试依赖于像这样进行所有初始化:

auto var = Type{};

(是的,我知道 brace-initializer ctor 与默认 ctor 的陷阱。所以请不要评论!)

我希望这会正确地“清零”或初始化 var 的内存。

但是在 VS 2013 Update 2 中,我看到了这个:

#include <string>
#include <iostream>

using namespace std;


struct B
{
    double g[10];
    std::string str;
};

struct C
{
    double g[10];
};

struct A
{
    double a[3];
    double b = 0;
    double d;
    struct B b_stuff;
    struct C c_stuff;
    A() : b_stuff{}, c_stuff{} {}
};

int main()
{
    auto a = A{};
    double big[50] = {};

    for(auto b : a.b_stuff.g) { cout << b << " "; }
    cout << endl;
    cout << endl;
    for(auto b : a.c_stuff.g) { cout << b << " "; }
    cout << endl;
    cout << endl;
    for (auto b : big) {  cout << b << " "; }

    return 0;
}

输出是这样的:

-9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061

0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

使用 GCC 4.7.2:

0 0 0 0 0 0 0 0 0 0 

0 0 0 0 0 0 0 0 0 0 

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 

我读过这篇文章,但我看不出这种非归零行为的原因:

http://en.cppreference.com/w/cpp/language/value_initialization http://en.cppreference.com/w/cpp/language/aggregate_initialization

那么,VS 2013 有问题吗?为什么它不将 a.b_stuff.g 数组归零?

最佳答案

Visual C++ 有 a long and storied history of value initialization bugs .我相信Bug 746973是你在这里偶然发现的。

关于c++ - 值初始化与聚合初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24676686/

相关文章:

c++ - 我不小心创建了一个病毒。这怎么是病毒?

c++ - QSerialPort 的 readAll() 不包括最后发送的响应

c++ - 有没有办法检测 const 合格对象的构造?

qt - 如何使用自定义事件手动使用 gst_app_src_push_buffer()

c++ - Visual Studio 2013 代码分析卡在 native 代码上

c++ - 使用 Opencv 从 Macbook Pro iSight 捕获

c++ - OpenCV 无法读取 AVI 文件

c++ - C++1z 范围的状态?

visual-studio - 如何选择当前项目进行查找和替换

c++ - 无法打开包含文件 'afxwin.h' :no such header fileor directory in vs 2013 c++