c++language-lawyerstdarray

Constructing a `std::array` with braces containing fewer elements than it can hold?


If I construct a std::array<T, N> with braces and give it fewer than N items, are those items zero-initialized? (Or are they left default-initialized?) If I give it zero items (i.e., = {}) then I believe it zero-initializes all elements.

I can't find an explicit answer to this simple question. Since std::array uses aggregate initialization when used like std::array<int, 2> x = { 1 };, that leads to https://en.cppreference.com/w/cpp/language/aggregate_initialization for rules on aggregate initialization. There, the only mention I see of this case is "If the size of the array is specified and it is larger than the number of characters in the string literal, the remaining characters are zero-initialized." but that's in the "Character arrays" section, so seems like it's not generally true. On the other hand, using constexrp as a UB detector indicates that they are zero'd: https://godbolt.org/z/zE9xKvbrq

Related:


Solution

  • Aggregate initialization zeroes (value-initializes, to be exact) the elements that don't otherwise have initializers.

    [dcl.init.aggr]/5.2

    For a non-union aggregate, each element that is not an explicitly initialized element is initialized as follows:

    — If the element has a default member initializer ([class.mem]), the element is initialized from that initializer.

    — Otherwise, if the element is not a reference, the element is copy-initialized from an empty initializer list ([dcl.init.list]).

    — Otherwise, the program is ill-formed.