Home > Backend Development > C++ > body text

Why Does gcc and clang Require a Default Member Initializer Even with a Default Constructor?

Barbara Streisand
Release: 2024-10-28 06:46:02
Original
233 people have browsed it

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
Copy after login

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>
Copy after login

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>
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!