Why Aggregate Initialization Fails with Explicitly Defaulted or Deleted Constructors in C 20
In C 20, aggregate initialization of structs with explicitly defaulted or deleted constructors is no longer supported. This change is a result of a revision in the C standard. Before C 20, aggregate initialization was allowed for structs that either had no constructors or only had explicitly defaulted or deleted constructors. However, in C 20, the standard was updated to state that aggregate initialization is only allowed for structs with no user-declared or inherited constructors.
Reasoning Behind the Change
The change was introduced to address the problem of unexpected and confusing initialization behavior. In earlier versions of C , explicitly defaulted or deleted constructors could allow aggregate initialization, even when it was not intended. This could lead to unexpected conversions and errors. By eliminating aggregate initialization in these cases, the standard ensures that initialization always occurs through the constructor(s), resulting in consistent and predictable behavior.
Example
Before C 20, the following code would have compiled without error:
<code class="cpp">struct Foo { Foo() = default; int bar; }; auto test = Foo { 0 }; // Aggregate initialization</code>
However, in C 20, the same code raises a compiler error, as the constructor is explicitly defaulted and aggregate initialization is no longer allowed. To fix the issue, the explicitly defaulted constructor can be removed or the initialization can be done explicitly using the constructor:
<code class="cpp">auto test = Foo(0); // Constructor initialization</code>
Impact on Coding Practices
While explicitly defaulting or deleting constructors was previously seen as a good practice, the change in the C 20 standard suggests that it is no longer beneficial. In C 20 and later versions, it is recommended to rely on implicit default constructor behaviour and avoid explicitly defaulting or deleting constructors unless there is a specific reason to do so.
The above is the detailed content of Why Does Aggregate Initialization Fail with Explicitly Defaulted or Deleted Constructors in C 20?. For more information, please follow other related articles on the PHP Chinese website!