Home > Backend Development > C++ > body text

Is std::array Default-Initialized in C 11?

Linda Hamilton
Release: 2024-10-30 11:47:02
Original
923 people have browsed it

Is std::array Default-Initialized in C  11?

Default Initialization of std::array

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!