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
.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.
std::array was provided by the library makers to discourage the C-style arrays, and yet avoid
std::vectors when the size is known at the compile time.
The two main reasons I understand are:
std::arrayimplements STL's interfaces for collection-types, allowing an
std::arrayto 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_value2are both semantically identical and cause pointer decay because the receiving function does not know the
by_referenceboth requires that
Uby a known compile-time constant, but preserve
So if you avoid array decay by using
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
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_reference techniques but with messier syntax).
std::array adds a 5th way:
template<typename T, size_t N> void by_stdarray( const std::array<T,N>& array )