Skip to content

clang-16: Incorrect "must explicitly initialize the member" error in function-local classΒ #62559

@vogelsgesang

Description

@vogelsgesang

See https://godbolt.org/z/zoxs4nae4 for a self-contained example.
Both GCC and Clang 15 accept the code. Clang 16 and Clang trunk reject it.

For

#include<memory>

class TypeErased {
    public:
    virtual ~TypeErased();
};

template <typename T, typename... Args>
std::unique_ptr<TypeErased> make_type_erased(Args&&... args) {
   struct TypeErasureWrapper : public TypeErased {
      T content;
      TypeErasureWrapper(Args&&... args) : content{std::forward<Args>(args)...} {}
      ~TypeErasureWrapper() override {}
   };

   return std::make_unique<TypeErasureWrapper>(std::forward<Args>(args)...);
}

class NoDefaultConstructor {
    public:
    NoDefaultConstructor(int);
};


auto testNoDefaultConstructor() {
    return make_type_erased<NoDefaultConstructor>(1);
}

The error message from Clang 16 does not make sense to me:

<source>:12:7: error: constructor for 'TypeErasureWrapper' must explicitly initialize the member 'content' which does not have a default constructor
      TypeErasureWrapper(Args&&... args) : content{std::forward<Args>(args)...} {}
      ^                                 ^

Clang is complaining that we would not initialize content, but on the very same line we are actually initializing it.

The error does not occur if the class has a default constructor or if I define TypeErasureWrapper outside the function, as shown in https://godbolt.org/z/YYzhWPnKx

Metadata

Metadata

Assignees

No one assigned

    Labels

    clang:diagnosticsNew/improved warning or error message in Clang, but not in clang-tidy or static analyzerconfirmedVerified by a second partyregression

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions