Home > Backend Development > C++ > Why Does GCC and Clang Throw \'Default Member Initializer Required\' When Using a Class as a Default Argument?

Why Does GCC and Clang Throw \'Default Member Initializer Required\' When Using a Class as a Default Argument?

Barbara Streisand
Release: 2024-10-26 10:49:02
Original
579 people have browsed it

Why Does GCC and Clang Throw

Understanding the Compiler Error: "Default Member Initializer Required Before the End of Its Enclosing Class"

This issue arises when attempting to define a default member initializer for a class member within a function that utilizes that class as a default argument value. Compilers like gcc and clang encounter difficulties with this construct, while msvc2017 handles it successfully.

Consider the following code snippet:

<code class="cpp">class Downloader
{
public:
    struct Hints
    {       
        int32_t numOfMaxEasyHandles = 8;
    };

    static Downloader *Create(const Hints &amp;hints = Hints());
};</code>
Copy after login

The provided code intends to define a default value for the numOfMaxEasyHandles member of the Hints struct, which is utilized as a default argument in the Create function. However, gcc and clang fail to compile this code, issuing the error:

default member initializer for 'Downloader::Hints::numOfMaxEasyHandles' required before the end of its enclosing class
Copy after login

Reason for the Error

This error occurs due to a bug in gcc and clang pertaining to the handling of default member initializers within classes that are used as default arguments in functions. The compilers expect the default member initializer to be defined within the class definition itself, rather than within the function body.

Possible Workarounds

To resolve this issue, there are two potential workarounds:

  1. Uncommenting Hints(){}: Adding an empty constructor to the Hints struct alleviates the compiler error. However, this approach may not be desirable as it defeats the purpose of having a default member initializer.
  2. Using Hints() = default: This statement explicitly defines a default constructor for the Hints struct. While it eliminates the compiler error in msvc2017, it renders the code incompatible with gcc and clang due to their aforementioned bug.

The above is the detailed content of Why Does GCC and Clang Throw \'Default Member Initializer Required\' When Using a Class as a Default Argument?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template