Home >Backend Development >C++ >Why does GCC 4.6.1 throw an error when initializing a `std::array` 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>
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>
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>
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!