In C++ what is the point of std::array if the size has to be determined at compile time?
Ease of programming
std::array
facilitates several beneficial interfaces and idioms which are used in std::vector
. With normal C-style arrays, one cannot have .size()
(no sizeof
hack), .at()
(exception for out of range), front()/back()
, iterators, so on. Everything has to be hand-coded.
Many programmers may choose std::vector
even for compile time known sized arrays, just because they want to utilize above programming methodologies. But that snatches away the performance available with compile time fixed size arrays.
Hence std::array
was provided by the library makers to discourage the C-style arrays, and yet avoid std::vector
s when the size is known at the compile time.
The two main reasons I understand are:
std::array
implements STL's interfaces for collection-types, allowing anstd::array
to be passed as-is to functions and methods that accept any STL iterator.- To prevent array pointer decay... (below)
...this is the preservation of type information across function/method boundaries because it prevents Array Pointer Decay.
Given a naked C/C++ array, you can pass it to another function as a parameter argument by 4 ways:
void by_value1 ( const T* array )
void by_value2 ( const T array[] )
void by_pointer ( const T (*array)[U] )
void by_reference( const T (&array)[U] )
by_value1
andby_value2
are both semantically identical and cause pointer decay because the receiving function does not know thesizeof
the array.by_pointer
andby_reference
both requires thatU
by a known compile-time constant, but preservesizeof
information.
So if you avoid array decay by using by_pointer
or by_reference
you now have a maintenance problem every time you change the size of the array you have to manually update all of the call-sites that have that size in U
.
By using std::array
it's taken care of for you by making those functions template
functions where U
is a parameter (granted, you could still use the by_pointer
and by_reference
techniques but with messier syntax).
...so std::array
adds a 5th way:
template<typename T, size_t N>
void by_stdarray( const std::array<T,N>& array )