Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

discrepancy between clang and g++ in dealing with const objects [duplicate]

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?

like image 507
vsoftco Avatar asked Dec 20 '14 22:12

vsoftco


2 Answers

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
like image 66
Kerrek SB Avatar answered Oct 20 '22 01:10

Kerrek SB


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 type T, T shall be a class type with a user-provided default constructor.

Clearly, the type doesn't have a user-provided default constructor.

like image 26
Dietmar Kühl Avatar answered Oct 20 '22 01:10

Dietmar Kühl