In C++11 std::array
is defined to have contiguous storage and performance that is no worse than an array, but I can't decide if the various requirements of the standard imply that std::array has the same size and memory layout as a normal array. That is can you count on sizeof(std::array<int,N>) == sizeof(int)*N
or is that implementation specific?
In particular, is this guaranteed to work the way you would expect it to:
std::vector< std::array<int, N> > x(M);
typedef int (*ArrayPointer)[N];
ArrayPointer y = (ArrayPointer) &x[0][0];
// use y like normal multidimensional array
It works in the two compilers I tried (GNU & Intel). Furthermore, all the 3rd party documentation I could find (like this), states that std::array is just as memory efficient as a plain array, which combined with the contiguous requirement would imply that it must have identical memory layout. However I can't find this requirement in the standard.
23.3.2 Class template array
, and indeed, searching the standard forsizeof
seems to only turn up the following guarantees for me:char
and its variants are1
, andnullptr
has the same sizeof asvoid*
. – Meeksstatic_assert(sizeof(std::array<T,N>) == sizeof(T)*N)
for all types in your code as a tripwire for an unusual library implementation (or some alignment option which causesstd::array
to align differently). If the sizes are equal the layout must be the same. – Countertype