Home > Article > Backend Development > Why Does GCC Fail to Initialize std::array with Initialization Lists?
Initialization Lists and std::array: A GCC Bug
The std::array class in the C Standard Library provides a fixed-size array container. It's commonly believed that this class supports initialization lists.
However, using GCC 4.6.1, attempts to initialize std::array instances using the following syntax fail:
<code class="cpp">std::array<std::string, 2> strings = { "a", "b" }; std::array<std::string, 2> strings({ "a", "b" });</code>
Despite initialization lists working with std::vector, this behavior with std::array has raised questions about the C standard or a potential GCC issue.
std::array's Inner Workings
std::array is essentially a struct that encapsulates an array. Its structure resembles:
<code class="cpp">template<typename T, int size> struct std::array { T a[size]; };</code>
Unlike std::vector, which has a constructor accepting initializer lists, std::array lacks such a constructor.
Aggregate Initialization
Although std::array doesn't have an explicit constructor for initialization lists, it's considered an aggregate type in C 11. As such, it can be aggregate initialized. However, to initialize the array within the struct, an additional set of curly braces is required:
<code class="cpp">std::array<std::string, 2> strings = {{ "a", "b" }};</code>
Potential GCC Bug
The C standard allows the omission of the extra curly braces in such initialization. Therefore, it's likely that GCC's inability to handle this syntax without them is a bug.
The above is the detailed content of Why Does GCC Fail to Initialize std::array with Initialization Lists?. For more information, please follow other related articles on the PHP Chinese website!