Consider the code:
struct Foo
{
int x = 10;
};
int main()
{
const Foo foo;
}
It compiles under g++ http://coliru.stacked-crooked.com/a/99bd8006e10b47ef, however spits an error under clang++ http://coliru.stacked-crooked.com/a/93f94f7d9625b579 :
error: default initialization of an object of const type
'const Foo' requires a user-provided default constructor
I am not sure who's right here. Why do we need a default ctor since we perform in-class initialization?
An object of class type may only be default-initialized if it has a user-provided default constructor. From [dcl.init]/7:
If a program calls for the default initialization of an object of a const-qualified type
T
,T
shall be a class type with a user-provided default constructor.
Your class Foo
doesn't have that; the presence of a brace-or-equals-initializer does not create a user-provided default constructor. Rather, your class has an implicitly defined default constructor, whose action incorporates the initialization as requested by the brace-or-equals-initializer. (Clang is right.)
([dcl.fct.def.default], in particular paragraph 5, relates the definitions of "user-provided", "explicitly defaulted", "implicitly declared" and "defined as deleted". The entire section is worth knowing.)
By the way, it's easy to avoid default-initialization in C++11:
const Foo foo {}; // hunky-dory
clang seems to be right according to 8.5 [dcl.init] paragraph 7 last sentence:
If a program calls for the default initialization of an object of a
const
-qualified typeT
,T
shall be a class type with a user-provided default constructor.
Clearly, the type doesn't have a user-provided default constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With