使用默认值初始化 std::数组
initialisation of std::array with default values
我偶然发现了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::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
由于int
是一个non-class
a
数组中元素的值是indeterminate
那么它们可能只是驻留在分配给a
元素的位置的垃圾东西。这就是为什么你不时看到不同的结果。
简而言之,这是一个undefined behavior
,因为您正在访问un-initialized variables
.
看起来像未定义的行为。如果要默认初始化std::array
,请改为执行以下操作:
std::array<int, 100> a = {};
相关文章:
- std::向量与传递值的动态数组
- std::vector的包装器,使数组的结构看起来像结构的数组
- 初始化具有非默认构造函数的std::数组项的更好方法
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 将 int 数组转换为 std::vector<int*>
- 输入std::数组时出现问题
- 缓存std::数组的选定元素,并在c++中自动保持其一致性
- 为什么std::vector比数组慢
- C++如何生成std::数组列表
- 捕获lambda中的std::数组
- 转换函数,将 std::数组的双精度作为参数或双精度作为参数单独转换
- 将无符号字符的向量存储在数组中会给我 std::bad_alloc
- 当 std::move 与 C 样式数组或不移动对象时会发生什么
- std::数组边界检查如何工作?
- 通过unique_ptr访问std::数组
- 我正在使用 std::bitset 并尝试创建两个大小为 100,000,000,000 的数组 std::bitset
- 对象的数组-STD ::数组 - 构造函数初始化问题
- 标准::数组<std::array<T、N2>、N> 数据成员上的括号运算符重载
- 从未来对象数组std::vector中检索值
- 如何将动态数组(std::vector)传递给odbc函数SQLBindParameter