Default initialization of std::array?

By definition, default initialization is the initialization that occurs when no other initialization is specified; the C++ language guarantees you that any object for which you do not provide an explicit initializer will be default initialized (C++11 §8.5/11). That includes objects of type std::array<T, N> and T[N].

Be aware that there are types for which default initialization has no effect and leaves the object’s value indeterminate: any non-class, non-array type (§8.5/6). Consequently, a default-initialized array of objects with such types will have indeterminate value, e.g.:

int plain_int;
int c_style_array[13];
std::array<int, 13> cxx_style_array;

Both the c-style array and std::array are filled with integers of indeterminate value, just as plain_int has indeterminate value.

Is there a syntax that will work on all arrays (including zero-sized arrays) to initialize all elements to their default value?

I’m guessing that when you say “to their default value” you really mean “initialize all elements to T{}“. That’s not default-initialization, it is value-initialization (8.5/7). You can request value initialization quite easily in C++11 by giving each declaration an empty initializer:

int plain_int{};
int c_style_array[13]{};
std::array<int, 13> cxx_style_array{};

Which will value-initialize all of the array elements in turn, resulting in plain_int, and all the members of both kinds of arrays, being initialized to zero.

Leave a Comment