Home > Article > Backend Development > Why Did C 11 Enable In-Class Initialization for Non-Static Members?
C 11 Allows In-Class Initialization: What Motivated the Change?
In the pre-C 11 era, in-class initialization was restricted to static const members. This limitation was attributed to the need to avoid linker complications in multi-translation unit scenarios.
However, with the introduction of C 11, these restrictions were relaxed, allowing in-class initialization for non-static and non-const members (§12.6.2/8).
While the original reasoning for the restrictions remains valid, C 11 implemented a solution that shifted the burden from Linkers to compilers. Instead of allowing multiple definitions, compilers now handle the initialization.
For non-static members with brace-or-equal-initializers, initialization is performed as per 8.5. Otherwise, if it's a variant member (9.5), no initialization occurs. In all other cases, default initialization (8.5) is performed.
Additionally, non-const static members marked with the constexpr specifier can now be initialized in-class (9.4.2).
This change simplifies code maintenance and provides greater flexibility, but it adds some complexity to the programming rules. For example, if a member has multiple initializers specified, the initialized value is determined by the constructor used. In cases where the default constructor is invoked, the in-class initializer is used. If a non-default constructor specifies a value, the in-class initializer is ignored.
Overall, the change reflects an increased emphasis on improved developer ergonomics without sacrificing linker reliability. Compilers now assume a more complex role to facilitate these features while maintaining a clean separation of concerns.
The above is the detailed content of Why Did C 11 Enable In-Class Initialization for Non-Static Members?. For more information, please follow other related articles on the PHP Chinese website!