c++c++11stlsizeofstdarray

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

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?


Solution

  • 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.