Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the size of std::array<T,0>?

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, and
  • sizeof(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?

like image 423
Fedor Avatar asked Jan 23 '26 17:01

Fedor


2 Answers

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.

like image 112
Mooing Duck Avatar answered Jan 25 '26 07:01

Mooing Duck


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() == 0
  • arr.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 nullptr

https://gcc.godbolt.org/z/nPbzWcahz

like image 39
0___________ Avatar answered Jan 25 '26 06:01

0___________



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!