Discrepancy between clang and g ++ when working with const objects

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 it 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'm not sure who is here. Why do we need ctor by default since we are initializing in the class?

+6
source share
2 answers

An object of type class can be initialized by default if it has a default constructor provided by the user. From [dcl.init] / 7:

If the program calls the default initialization of an object of type const-type T , T must be a class type with a user-supplied default constructor.

Your Foo class does not; having a parenthesis initializer or the same does not create a user-created default constructor. Rather, your class has an implicit default constructor, the action of which includes initializing as requested using the brace-or-equals-initializer element. (Klang is right.)

([dcl.fct.def.default], in particular clause 5, refers to 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 the default initialization in C ++ 11:

 const Foo foo {}; // hunky-dory 
+7
source

clang seems correct according to 8.5 [dcl.init] p. 7 of the last sentence:

If a program calls the default initialization of a const -qualified type T object, T must be a class type with a user-supplied default constructor.

Obviously, the type does not have a custom constructor by default.

+3
source

Source: https://habr.com/ru/post/979986/


All Articles