使用默认值初始化 std::数组

initialisation of std::array with default values

本文关键字:数组 std 初始化 默认值      更新时间:2023-10-16

我偶然发现了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 

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

请在 std::array 查看constructor

由于int是一个non-classa数组中元素的值是indeterminate那么它们可能只是驻留在分配给a元素的位置的垃圾东西。这就是为什么你不时看到不同的结果。

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

看起来像未定义的行为。如果要默认初始化std::array,请改为执行以下操作:

std::array<int, 100> a = {};