Home > Article > Backend Development > Is std::array Default-Initialized in C 11?
C 11 introduced the std::array data structure, which resembles C-style arrays but provides additional features such as template-based type specification and compile-time size determination. However, a common question arises: does declaring a std::array without explicit initialization result in default initialization for each element?
According to the C language specification (§8.5/11), any object without an explicit initializer undergoes default initialization. This includes std::array objects. Default initialization initializes objects of non-class types, but for objects of class types (which std::array is), it invokes the default constructor.
However, the cppreference documentation mentions that the default constructor "default-constructs or copy-constructs every element of the array." This implies that std::array may not perform default initialization for each element.
Answer:
Yes, by default, declaring a std::array without explicit initialization will default-initialize all elements as per the C 11 specification. This behavior applies to both zero-sized and non-zero-sized arrays.
Value Initialization vs. Default Initialization:
Note that value initialization (8.5/7) differs from default initialization. Value initialization assigns elements the default value of their respective types, which is typically zero or false for primitive types. To explicitly perform value initialization, one can use curly braces with an empty initializer:
<code class="cpp">std::array<int, 13> cxx_style_array{}; // Value-initialize all elements to 0</code>
This explicitly sets all elements to the default value of int, which is 0.
The above is the detailed content of Is std::array Default-Initialized in C 11?. For more information, please follow other related articles on the PHP Chinese website!