使用默认值初始化std :: array

时间:2017-07-14 02:07:05

标签: c++ arrays initialization

我偶然发现std::array的奇怪行为。某些容器(例如std::vector)会初始化所有单元格,因此int的向量默认情况下将是一个充满零的向量。我测试了std::array是否也是如此。我发现了两件事:

1)看起来大多数细胞都被初始化(但可能还有其他原因),有些则没有。

2)未初始化的细胞总是相同的。这适用于程序的单独执行以及单独的编译之间。考虑下面的输出。对于此代码:

std::array<int, 100> a;
for (auto x : a) std::cout << x << " ";

我现在想知道为什么这两件事情都是这样的。导致这种明显初始化的原因(可能是其他原因)以及为什么非初始化单元始终是相同的(有时eben具有与之前执行中相同的值)?

$ cocompile test.cpp
$ ./a.out
1583671832 1235456 1235456 1235456 1235456 1235456 0 0 0 0 
$ ./a.out
1539111448 1235456 1235456 1235456 1235456 1235456 0 0 0 0 
$ ./a.out
1509472792 1235456 1235456 1235456 1235456 1235456 0 0 0 0 
$ cocompile test.cpp
$ ./a.out
1551280664 32767 1551280664 32767 55136256 1 0 1 71644448 1 71644352 1 0 0 0 0 0 0 0 0 
$ ./a.out
1413601816 32767 1413601816 32767 192815104 1 0 1 407872800 1 407872704 1 0 0 0 0 0 0 0 0 
$ ./a.out
1542519320 32767 1542519320 32767 63897600 1 0 1 129918240 1 129918144 1 0 0 0 0 0 0 0 0 
$ cocompile test.cpp
$ ./a.out
1510054424 32767 1 0 1510054368 32767 145269321 1 1510054400 32767 1510054400 32767 1510054424 32767 96362496 1 0 1 145265952 1 145265856 1 0 0 0 0 0 0 0 0
$ ./a.out
1394678296 32767 1 0 1394678240 32767 378704457 1 1394678272 32767 1394678272 32767 1394678296 32767 211738624 1 0 1 378701088 1 378700992 1 0 0 0 0 0 0 0 0 
$ ./a.out
1436727832 32767 1 0 1436727776 32767 353342025 1 1436727808 32767 1436727808 32767 1436727832 32767 169689088 1 0 1 353338656 1 353338560 1 0 0 0 0 0 0 0 0 

2 个答案:

答案 0 :(得分:0)

std::array initializes the array following the rules of aggregate initialization (note that default initialization may result in indeterminate values for non-class T)的构造函数。

请在std::array

处查看constructor

由于intnon-classa数组中的元素值为indeterminate,因此它们可能只是位于分配给元素的位置的垃圾内容您的a。这就是为什么你不时会看到不同的结果。

简而言之,这是undefined behavior,因为您正在访问un-initialized variables

答案 1 :(得分:0)

看起来像未定义的行为。如果您要默认初始化PropertySource,请改为执行此操作:

std::array