Std :: array size 0

What does it mean to have std::array<int,0> , an array of zero size?

I went through similar questions in SO before posting this, and all of these questions are about a simple array type and C language, and most of them say that it is illegal. But in C ++ array<int,0> allowed.

According to cppreference.com

There is a special case for an array of zero length (N == 0). In this case, array.begin() == array.end() , which is some unique value. The effect of calling front() or back() in an array of size zero: undefined.

Why is it not defined as illegal?

+7
c ++ stdarray
source share
2 answers

What does it mean to have std :: array, an array of zero size?

Same as, for example, empty std::vector or empty std::set .

Why is it not defined as illegal?

it is advisable to make this legal, because it means that universal programming should not handle the special case where the size of std::array is the result of calculating compilation time.

it is possible to define it as legal due to the specialization of templates. For example, the implementation that ships with Visual C ++ specializes in std::array in a way 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 believe that every compiler implements std::array like this.

+10
source share

std :: array is treated like other standard containers that may be empty. Thus, specializing std::array with N equal to zero defines an empty container.

+2
source share

All Articles