I have the code:
class A {
public:
A() = default;
private:
int i = 1;
};
int main() {
const A a;
return 0;
}
It compiles
Since C++17, this code is correct, as is the similar code from this question:
struct MyClass1 { int i{}; };
struct MyClass2 { const MyClass1 m; };
MyClass2 a;
clang 8.0.0 rejects this latter code even with -std=c++17
which means that clang 8.0.0 has a bug.
In C++17 the following new text was added as [dcl.init]/7 (as per P0490R0 in response to DR 253):
A class type
T
is const-default-constructible if default-initialization ofT
would invoke a user-provided constructor ofT
(not inherited from a base class) or if
- each direct non-variant non-static data member
M
ofT
has a default member initializer or, ifM
is of class typeX
(or array thereof),X
is const-default-constructible,- if
T
is a union with at least one non-static data member, exactly one variant member has a default member initializer,- if
T
is not a union, for each anonymous union member with at least one non-static data member, exactly one non-static data member has a default member initializer, and- each potentially constructed base class of
T
is const-default-constructible.If a program calls for the default-initialization of an object of a const-qualified type
T
,T
shall be a const-default-constructible class type or array thereof.
Prior to C++17 there was no such text; an object defined as const
must either have an initializer or a user-provided constructor. So, prior to C++17, clang was correct and g++ was bugged to accept the code without diagnostic.