Home  >  Article  >  Backend Development  >  Why Does Explicitly Defaulting or Deleting Constructors Prevent Aggregate Initialization in C 20?

Why Does Explicitly Defaulting or Deleting Constructors Prevent Aggregate Initialization in C 20?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 16:28:03212browse

Why Does Explicitly Defaulting or Deleting Constructors Prevent Aggregate Initialization in C  20?

Why explicit default or deleted constructors prevent aggregate initialization in C 20

C 20 introduces a change that affects aggregate initialization. Previously, allowed structs could have explicitly defaulted or deleted constructors. However, this is no longer the case.

Reasoning

The change is motivated by the desire to improve initialization semantics in C and make them more consistent. Allowing aggregate initialization with explicitly defaulted or deleted constructors could lead to confusing and unexpected behavior.

For example, consider the following code:

<code class="cpp">struct X {
  int i{4};
  X() = default;
};

int main() {
  X x1(3); // ill-formed - no matching c’tor
  X x2{3}; // compiles!
}</code>

In C 17, x2 would initialize the i member variable to 3. However, this behavior was inconsistent with user-defined constructors. This change resolves this inconsistency.

Alternative Solutions

To resolve the error, explicitly default or deleted constructors should not be used for aggregate types. Instead, consider omitting the constructor or using a user-defined constructor.

The above is the detailed content of Why Does Explicitly Defaulting or Deleting Constructors Prevent Aggregate Initialization in C 20?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn