C 11 Aggregate Initialization for Classes with Non-Static Member Initializers
In C 11, a class or struct is considered an aggregate if it meets specific criteria, including having no user-defined constructors, no brace-or-equal initializers for non-static data members, and no private or protected non-static data members.
However, in standard C 11, adding non-static member initializers to a class or struct changes its status as an aggregate. This is because member initializers are similar to user-defined constructors, which disqualifies the class or struct from being an aggregate. This change in definition can lead to unexpected behavior.
In the example provided:
struct A { int a = 3; int b = 3; }; A a{0,1}; // ???
The class A is no longer considered an aggregate due to the presence of in-class member initializers. As a result, the aggregate initialization A a{0,1}; is invalid.
This behavior was revised in C 14, where the presence of non-static member initializers no longer prevents a class or struct from being an aggregate. Therefore, in C 14, the aggregate initialization of A is valid.
It is important to note that the C standard has undergone changes, and it is essential to check the latest versions of the standard or use a compliant C 14 or later compiler to ensure correct interpretation of code involving aggregate initialization and non-static member initializers.
The above is the detailed content of Can a C class with non-static member initializers be an aggregate?. For more information, please follow other related articles on the PHP Chinese website!