2014-07-10 279 views
0

我面临着一个值初始化与集合初始化混合的问题。 到目前为止,我试图依靠做我所有的初始化是这样的:值初始化vs集合初始化

自动无功=类型{};

(是的,我知道大括号初始化男星VS默认构造函数的陷阱的。因此,没有有关意见,请!)

我希望这会正确“归零”或init VAR的记忆。

但在VS 2013更新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数组清零?

+0

你是对的,是一个MSVC错误。你正确地初始化'b_stuff'(我在写回答时已经错过了那行)。 – Manu343726

+0

呵呵,“好”。我开始恐慌/希望我错过了一些明显的事情。如果这是真的MSVC的错误则是坏消息...... –

+0

尝试使用级值初始化,其允许的,因为C++ 11,但我不知道,如果微软的人实现了它:HTTP:/ /coliru.stacked-crooked.com/a/e1e6d42289ce54ee – Manu343726

回答