Search code examples
c++c++11initializationdefault-constructorstdarray

Default initialization of std::array?


With C++11 std::array, do I have the guarantee that the syntax std::array<T, N> x; will default-initialize all the elements of the array ?

EDIT: if not, is there a syntax that will work on all arrays (including zero-sized arrays) to initialize all elements to their default value?

EDIT: on cppreference, the default constructor description says:

(constructor) (implicitly declared) (public member function)
default-constructs or copy-constructs every element of the array 

so the answer may be yes. But I would like to be sure of that according to the standard or future standard.


Solution

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