Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 460
Daniel Langr Avatar asked Jan 18 '26 01:01

Daniel Langr


1 Answers

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.

like image 82
Alan Birtles Avatar answered Jan 20 '26 17:01

Alan Birtles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!