Home > Backend Development > C++ > Why does GCC 4.6.1 throw an error when initializing a `std::array` with braces?

Why does GCC 4.6.1 throw an error when initializing a `std::array` with braces?

Mary-Kate Olsen
Release: 2024-10-29 06:42:31
Original
629 people have browsed it

Why does GCC 4.6.1 throw an error when initializing a `std::array` with braces?

std::array Initialization with Braces

In C , there are two common ways to create a std::array using initialization lists:

<code class="cpp">std::array<std::string, 2> strings = { "a", "b" };
std::array<std::string, 2> strings({ "a", "b" });</code>
Copy after login

However, if you encounter a compilation error about "expected primary-expression before ',' token" with GCC 4.6.1, it is due to a slight peculiarity in std::array.

Unlike std::vector, which has a constructor that explicitly takes an initializer list, std::array is defined as a struct:

<code class="cpp">template<typename T, int size>
struct std::array
{
  T a[size];
};</code>
Copy after login

As such, it does not have a constructor that directly accepts an initializer list. Instead, it can be initialized using aggregate initialization.

To correctly aggregate initialize an array inside the std::array struct, an extra set of curly braces is required:

<code class="cpp">std::array<std::string, 2> strings = {{ "a", "b" }};</code>
Copy after login

It is worth noting that the C standard suggests that the extra braces should be optional in this scenario. Therefore, the compilation error you experienced with GCC 4.6.1 is likely a bug in the compiler.

The above is the detailed content of Why does GCC 4.6.1 throw an error when initializing a `std::array` with braces?. For more information, please follow other related articles on the PHP Chinese website!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template