Unlike C array, std::array is allowed to have zero length. But the current implementations differ in how std::array<T,0> is implemented, in particular the sizes of the object are different.
This program
#include <array>
int main() {
return sizeof(std::array<int,0>);
}
suggests that
sizeof(std::array<T,0>) == sizeof(T) in Clang's libc++ and Microsoft's STL, andsizeof(std::array<T,0>) == 1 in GCC's libstdc++.Are all implementations correct here and libstdc++ just better optimizes std::array<T,0>? Or smaller size here results in some other disadvantages, which are the reason that other implementations do not go that way?
https://eel.is/c++draft/array.zero
So far as I can tell, the size is unspecified by the standard.
sizeof(std::array<T,0>) == sizeof(T) is probably easier to implement, and preserves alignment, though I'm unsure what the value of that would be. sizeof(std::array<T,0>) == 1 is probably trickier to implement, and does not preserve alignment, but saves a few bytes.
The C++ object model requires sizeof of any complete object type to be at least 1, so sizeof(std::array<T,0>) >= 1, but the standard does not mandate an exact value for that sizeof - only that it be nonzero.
What is guaranteed:
arr.size() == 0arr.begin() == arr.end()arr.data() equals begin() (and you must not dereference it)std::array<T, 0>, data() is valid to call, but the standard does not require it to be nullptrhttps://gcc.godbolt.org/z/nPbzWcahz
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With