I have just asked two questions about array and value initialization here and here. But with this code, I'm lost:
#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;
}
As expected, f1
return arbitrary values as its values are not zero-initialized. But f2
seems to return exclusively zero values:
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
Personally I thought that f2
will create an array with arbitrary values and copy/move it to x
. But it does not seem to be the case.
So, I have two questions:
- Why?
- Do C++11
std::array<T, N>
and C-styleT[N]
have the same behaviour in such a situation?