c++libc++stdarray

Why is std::array<T,0> sized and aligned according to T in libc++?


In libc++, the specialization of std::array<T,0> has a member (const) char array, which is aligned and sized according to T (source). I wonder what is the reason for this implementation since this member (__elems_) does not seem to be used anywhere. For comparison, libstdc++ uses an empty member, and Microsoft STL uses an empty member if T is not default-constructible (otherwise, it creates a single-element array).

Live demo of the difference: https://godbolt.org/z/1o167na6z


Solution

  • std::array is allowed to have a zero size but the underlying c arrays can't be zero-sized. Therefore the implementations will need some special case to handle this.

    The standard doesn't specify what this implementation must be or really place many constraints on the behaviour, calling front() or back() is undefined behaviour. There is one constraint that array.begin() == array.end(). As there are not many constraints you'd expect different implementations to use different workarounds for it.

    Libc++ originally used a single element array but this doesn't work with non-default constructible types. In order to maintain ABI compatibility this was replaced with a char array of the same size.