jeudi 1 août 2019

clang won't default construct const class member

I was thinking this is a clang bug, but just want to check I have my understanding correct of what should be happening.

I have a default-constructible class (the content of the class isn't relevant, I think, just that it's default-constructible)

struct MyClass1
{
    int i{};
};

and another class that contains a const member of that class type

struct MyClass2
{
    const MyClass1 m;
};

then at some point, I create a variable of type MyClass2 like this

MyClass2 a;

My understanding is that this should default-construct an instance of MyClass2, which in turn should default-construct its const member instance of MyClass1, but compiling with clang (tested versions 4.0 through to 8) gives me the compile error

error: call to implicitly-deleted default constructor of 'MyClass2'

note: default constructor of 'MyClass2' is implicitly deleted because field 'm' of const-qualified type 'const MyClass1' would not be initialized

gcc compiles this as expected (versions 5 through 9), and clang compiles if I add an initialiser in for the class member like const MyClass1 m{} or the variable in main MyClass2 a{}.

What made me start to think that my understanding is incorrect is that gcc gives a similar error when I remove the initialiser from MyClass1::i (I'd have expected it to compile and just have i be initialised), as well as when I make MyClass1 an empty struct (which I thought should be fine).

Aucun commentaire:

Enregistrer un commentaire