Home > Backend Development > C++ > Why does std::array require double curly braces for initializer lists while std::vector doesn't?

Why does std::array require double curly braces for initializer lists while std::vector doesn't?

Mary-Kate Olsen
Release: 2024-11-07 03:40:03
Original
814 people have browsed it

Why does std::array require double curly braces for initializer lists while std::vector doesn't?

C Initializer_List Behavior Discrepancy for std::vector and std::array

When using initializer lists for C containers, a perplexing difference arises between std::vector and std::array. Let's explore the reasons behind this behavior.

Problem:

Consider the following code:

std::vector<int> x{1,2,3,4};
std::array<int, 4> y{{1,2,3,4}};
Copy after login

Why is it necessary to use double curly braces for std::array but not for std::vector?

Answer:

The behavior stems from the nature of std::array as an aggregate. Aggregates do not have user-declared constructors, including ones that accept initializer lists. Consequently, aggregate initialization for std::array is performed through "old style" initialization using the = syntax:

std::array<int, 4> y = { { 1, 2, 3, 4 } };
Copy after login

In this old style, extra braces may be omitted, resulting in the equivalent code:

std::array<int, 4> y = { 1, 2, 3, 4 };
Copy after login

However, this brace elision is only allowed when using the old style initialization with the = syntax. Direct list initialization, which does not use the = syntax, does not allow brace elision. This limitation is governed by C 11 §8.5.1/11.

Proposed Resolution:

A defect report (CWG defect #1270) has been raised to address this limitation. If the proposed resolution is adopted, brace elision will be allowed for all forms of list initialization, including the following:

std::array<int, 4> y{ 1, 2, 3, 4 };
Copy after login

This change would bring consistency to the behavior of std::vector and std::array when using initializer lists.

The above is the detailed content of Why does std::array require double curly braces for initializer lists while std::vector doesn't?. 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