2

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).

John Ilacqua
  • 906
  • 5
  • 19
  • This quote from cppreference explains gcc's behaviour from my last paragraph: "The implicitly-declared or defaulted default constructor for class T is undefined (until C++11)defined as deleted (since C++11) if any of the following is true: - T has a const member without user-defined default constructor or a default member initializer (since C++11)." – John Ilacqua Aug 01 '19 at 23:49
  • There is a notion that const objects must be initialized, and in some language versions the interpretation has been that `m` itself requires an initializer even if it wouldn’t change anything. That variation may be the source of this implementation divergence. – Davis Herring Aug 02 '19 at 00:02
  • See [this answer](https://stackoverflow.com/a/57318531/1505939) specifically; your code is correct since C++17 – M.M Aug 02 '19 at 00:24

0 Answers0