Search code examples
c++stdarray

std::array of size zero


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 calling front() or back() on a zero-sized array is undefined.

Why isn't it defined as illegal?


Solution

  • 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.