Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::array of size zero

Tags:

c++

stdarray

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?

like image 264
InQusitive Avatar asked Mar 08 '15 16:03

InQusitive


2 Answers

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.

like image 144
Christian Hackl Avatar answered Oct 15 '22 08:10

Christian Hackl


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.

like image 22
Vlad from Moscow Avatar answered Oct 15 '22 09:10

Vlad from Moscow