Understanding the Compiler Error "Default Member Initializer Required Before Class End"
In this code snippet:
<code class="cpp">#include <cassert> #include <iostream> #include <cstdlib> class Downloader { public: struct Hints { int32_t numOfMaxEasyHandles = 8; }; static Downloader *Create(const Hints &hints = Hints()); }; Downloader* Downloader::Create(const Hints &hints) { std::cout << hints.numOfMaxEasyHandles << std::endl; return nullptr; }</code>
The error message "default member initializer required before the end of its enclosing class" is raised by Clang and GCC compilers while trying to define a default argument that constructs an instance of the struct Hints.
Reason for the Error
This error occurs because the default argument for the Create function is a non-trivial constructor, which requires a default member initializer to be defined within the declaration of the Hints struct. Without the member initializer, the compiler is unable to determine the initial values for the numOfMaxEasyHandles member when a default argument is used.
Solution
To fix the issue, the Hints struct should include a default member initializer, as follows:
<code class="cpp">struct Hints { int32_t numOfMaxEasyHandles = 8; Hints() {} // Default member initializer };</code>
With the default member initializer in place, both Clang and GCC will be able to compile the code successfully. Note that the Hints struct needs to define an explicit default constructor for this solution to work.
GCC and Clang Bug
One may notice that the following line:
<code class="cpp">Hints() = default;</code>
does not fix the issue for Clang and GCC. This is a known bug in these compilers, where default member initializers for non-trivial constructors are not recognized correctly in certain contexts, such as when the constructor is used as a default argument.
The above is the detailed content of Why Does \'Default Member Initializer Required Before Class End\' Error Occur When Using a Non-Trivial Constructor as a Default Argument?. For more information, please follow other related articles on the PHP Chinese website!