为什么std :: array <int,10> x不是零初始化但是std :: array <int,10> x = std :: array <int,10>()似乎是?

Vin*_*ent 14 c++ arrays initialization default-value c++11

我刚刚在这里这里询问了有关数组和值初始化的两个问题.但是使用这段代码,我迷路了:

#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;
}
Run Code Online (Sandbox Code Playgroud)

正如所料,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
Run Code Online (Sandbox Code Playgroud)

我个人认为这f2将创建一个具有任意值的数组并将其复制/移动到x.但似乎并非如此.

所以,我有两个问题:

  • 为什么?
  • 在这种情况下,C++ 11 std::array<T, N>和C风格T[N]是否具有相同的行为?

Pot*_*ter 14

使用{}()作为初始化程序,使用我们的without =,会导致值初始化.对于具有隐式声明的构造函数的类型,值初始化实现零初始化,顾名思义将每个基元元素设置为0.这可以在构造函数运行之前发生,但在这种情况下,构造函数不执行任何操作.

因为构造函数什么都不做(它很简单),所以可以看到未初始化的数据.

至于C风格的数组,如果你使用的行为是相似= {}的,而不是= T(),因为后者是非法的.T()会要求将临时数组对象分配给命名对象,但不能分配数组.= {}另一方面,为数组分配一个braced-initializer-list,而一个braced-initializer-list是一个特殊的语法结构,既不是表达式也不是对象.