What does it mean to have std::array<int,0>
,array of size zero?
I have gone through similar questions in SO before posting this, and all those
questions are regarding simple array type and for C language and most of them says that it is illegal. But in C++ array<int,0>
is allowed.
As per cppreference.com
There is a special case for a zero-length array (N == 0). In that case,
array.begin() == array.end()
, which is some unique value. The effect of callingfront()
orback()
on a zero-sized array is undefined.
Why isn't it defined as illegal?
What does it mean to have std::array,array of size zero?
The same as for example an empty std::vector
or an empty std::set
.
Why isn't it defined as illegal?
It is desirable to make it legal because it means generic programming does not have to handle a special case when the std::array
's size is the result of a compile-time calculation.
It is possible to define it as legal thanks to template specialisation. For example, the implementation that comes with Visual C++ specialises std::array
in a fashion similar to the following:
template<class T>
class array<T, 0> // specialisation
{
// ...
size_type size() const
{
return 0;
}
T elements[1]; // the raw array cannot have a size of 0
};
I suppose every compiler implements std::array
like that.
std::array is considered like other standard containers that can be empty. So the specialization of the std::array
with N equal to zero defines an empty container.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With