4

Consider following example:

#include <iostream>
#include <type_traits>

struct A
{
  //A() = default; // does neither compile with, nor without this line
  //A(){};         // does compile with this line
  int someVal{ 123 };


  void foobar( int )
  {
  };
};


int main()
{
    const A a;
    std::cout << "isPOD = " << std::is_pod<A>::value << std::endl;
    std::cout << "a.someVal = " <<a.someVal << std::endl;
}

See Live example

This does compile with g++ but does not compile with clang++, tried with following command: clang++ -std=c++11 -O0 main.cpp && ./a.out

Compile error from clang:

main.cpp:19:13: error: default initialization of an object of const type 'const A' requires a user-provided default constructor

I learned from This Stack Overflow Question, that non-POD classes get default constructor. This is even not necessary here because the variable has c++11-style default initialization

Why does this not for clang? Why does A() = default; not work, too?

Community
  • 1
  • 1
meddle0106
  • 1,292
  • 1
  • 11
  • 22

2 Answers2

5

This is addressed in CWG issue #253 which discusses the need for a user provided constructor for empty objects or objects whose subobjects are fully initialized (which is the case in your example).

Quoting part of the linked issue

Notes from the August, 2011 meeting:

If the implicit default constructor initializes all subobjects, no initializer should be required.

Technically it is an active issue but given that note it seems likely that it'll be resolved the way gcc chose to implement it.

Clang, on the other hand, has chosen to wait until the issue is resolved before implementing a solution.

In Clang, we're waiting for the issue to actually be resolved before we take a direction on it.

So, as it currently stands, clang is correct.

Praetorian
  • 106,671
  • 19
  • 240
  • 328
  • I think this thread should be closed as duplicate of remyabel's suggestion; perhaps post your answer on that thread also – M.M Feb 05 '15 at 07:41
  • @MattMcNabb Potatoswatter's answer on the other thread is more comprehensive than mine, so I don't want to add noise to that. – Praetorian Feb 05 '15 at 17:20
2

You quoted the answer yourself. In the SO answer that you linked, there is the following quote from the standard (section 6.8.6precisely):

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.

emphasis mine. The line

A() = default;

obviously does not provide a constructor, it does the opposite by telling the compiler that you don't want to provide one, thus your code doesn't compile. However, once you provide the constructor by uncommenting

 A(){}; 

it works fine. So, to summarize, the error that clang shows is per standard, and the behaviour of gcc is probably a bug.

SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105