Value-initializing std::array member?

Viewed 274

Let's suppose I have a class template that has a std::array member:

template<typename T>
class C {
public:
    C();

private:
    std::array<T, 42> a;
};

How do I define C::C such that a will always be value-initialized (not default-initialized)? ie such that the constructor calls T() to initialize every element of a - and that, for example, if T is int, then every element of a is guaranteed to be zero and not an indeterminant value?

int main() {
   C<int> c;
   assert(c.a[13] == 0); // ignoring private for exposition
}

UPDATE

Additional information for posterity:

  1. std::array is an aggregate type with a single element T[N]
  2. Initialization of std::array by an init-list is aggregate initialization
  3. Aggregate initialization with an empty init-list causes each element to not be explicitly initialized. Such elements are initialized as if by copy-initialization from an empty init-list.
  4. The array T[N] is therefore copy-initialized from an empty init-list. It is also an aggregate therefore 2 and 3 apply recursively.
  5. Each of the N elements of T[N] are copy-initialized from an empty init-list.
  6. Each T object is copy-list-initialized with an empty init-list as per [dcl.init.list]/3. The final clause of that chain is reached which reads:

Otherwise, if the initializer list has no elements, the object is value-initialized.

and voila. Initializing std::array with an empty init list {} causes its elements to be value-initialized.

1 Answers

You can use inline member initialization:

private:
    std::array<T, 42> a{};

If you absolutely want to do it with a constructor instead (why though?) then:

C()
    : a{}
{ }
Related