Zero-initializing elements of a std::array with a default member initializer

Viewed 5096

Suppose I have a class template like this:

template<typename T, size_t N>
struct S {
   std::array<T,N> a;
};

Is there a default member initializer I can place on a,

template<typename T, size_t N>
struct S {
   std::array<T,N> a = ???;
};

such that no matter what T is, the elements of a will always be initialized (never have indeterminant value)? I.e., even if T is a primitive type like int.

2 Answers

This:

template<typename T, size_t N>
struct S {
   std::array<T,N> a = {};
};

That will recursively copy-initialize each element from {}. For int, that will zero-initialize. Of course, someone can always write:

struct A {
    A() {}
    int i;
};

which would prevent i from being initialized. But that's on them.

std::array is an aggregate type. You can aggregate initialize it with empty braces {} and that will initialize accordingly the elements of the internal array of T that std::array holds.

Related