Home >Backend Development >C++ >Why Does gcc and clang Require a Default Member Initializer Even with a Default Constructor?
Understanding Compiler Error: "Default Member Initializer Required Before End of Class"
When attempting to compile the code below with gcc8.2 and clang7.0, users may encounter the following error message:
default member initializer for 'Downloader::Hints::numOfMaxEasyHandles' required before the end of its enclosing class
This error occurs due to a subtle issue with the default member initializer for the numOfMaxEasyHandles variable within the Hints struct of the Downloader class.
<code class="cpp">class Downloader { public: struct Hints { int32_t numOfMaxEasyHandles = 8; //Hints(){} // <= if I uncomment this all works gcc+clang+msvc //Hints() = default; // <= if I uncomment this neither clang no gcc works (msvc - works) }; };</code>
The underlying source of the error:
If the default constructor Hints() for the Hints struct is uncommented, the error message disappears. However, if the default constructor is replaced with Hints() = default;, the error persists in gcc and clang.
This behavior is a known bug in both gcc and clang. In such scenarios, the compiler requires the default member initializer for numOfMaxEasyHandles to be defined within the struct's definition itself, even though the default constructor is present.
MSVC's behavior:
In contrast, MSVC2017 does not exhibit this error and allows the code to compile without any issues. This is because MSVC handles default member initializers differently from gcc and clang.
Workaround:
To resolve the error in gcc and clang, one can simply define the default member initializer within the struct's definition:
<code class="cpp">struct Hints { int32_t numOfMaxEasyHandles = 8; };</code>
With this modification, the code should compile successfully in all three compilers.
The above is the detailed content of Why Does gcc and clang Require a Default Member Initializer Even with a Default Constructor?. For more information, please follow other related articles on the PHP Chinese website!