[英]Why std::array<int, 10> x is not zero-initialized but std::array<int, 10> x = std::array<int, 10>() seems to be?
我刚刚在这里和这里询问了有关数组和值初始化的两个问题。 但是使用这段代码,我迷路了:
#include <iostream>
#include <iomanip>
#include <array>
template <class T, class U = decltype(std::declval<T>().at(0))>
inline U f1(const unsigned int i)
{T x; return x.at(i);}
template <class T, class U = decltype(std::declval<T>().at(0))>
inline U f2(const unsigned int i)
{T x = T(); return x.at(i);}
int main()
{
static const unsigned int n = 10;
static const unsigned int w = 20;
for (unsigned int i = 0; i < n; ++i) {
std::cout<<std::setw(w)<<i;
std::cout<<std::setw(w)<<f1<std::array<int, n>>(i);
std::cout<<std::setw(w)<<f2<std::array<int, n>>(i);
std::cout<<std::setw(w)<<std::endl;
}
return 0;
}
正如预期的那样, f1
返回任意值,因为它的值不是零初始化的。 但是f2
似乎只返回零值:
0 0 0
1 61 0
2 0 0
3 0 0
4 297887440 0
5 32767 0
6 4196848 0
7 0 0
8 297887664 0
9 32767 0
就个人而言,我认为f2
将创建一个具有任意值的数组,并将其复制/移动到x
。 但似乎并非如此。
所以,我有两个问题:
std::array<T, N>
C ++ 11 std::array<T, N>
和C风格的T[N]
是否具有相同的行为? 使用{}
或()
作为初始化程序,使用我们的without =
,会导致值初始化。 对于具有隐式声明的构造函数的类型,值初始化实现零初始化,顾名思义将每个基元元素设置为0
。 这可以在构造函数运行之前发生,但在这种情况下,构造函数不执行任何操作。
因为构造函数什么都不做(它很简单 ),所以可以看到未初始化的数据。
对于C风格的数组,如果使用= {}
而不是= T()
,则行为类似,因为后者是非法的。 T()
会要求将临时数组对象分配给命名对象,但不能分配数组。 另一方面, = {}
将一个braced-initializer-list分配给数组,而braced-initializer-list是一个特殊的语法结构,既不是表达式也不是对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.