1

I was reading about default initialization in C++ on here. It says that:

If T is a const-qualified type, it must be a class type with a user-provided default constructor.

The example given on that link is (I've only shown program statements relevant to my question, others I've omitted):

struct T1 {};
int main()
{
    const T1 nd;    //  error: const class type with implicit ctor
}

But it compiles fine on gcc 4.8.1 & 4.9.2. I also compiled it with -std=c++14 option but it still compiles fine. Is this gcc extension or something else?

So, I think the reason behind successful compilation of above program is that there are no members in struct T1. So, no default initialization occurs here in this case. But if I add the one data member like:

struct T1 { int a; };
int main()
{
    const T1 nd;    //  error: const class type with implicit ctor
}

Then compiler gives appropriate error messages as following:

6 11 [Error] uninitialized const 'a' [-fpermissive]
2 8 [Note] 'const struct T1' has no user-provided default constructor
3 8 [Note] and the implicitly-defined constructor does not initialize 'int T1::a'

So, shouldn't the statment be written like this?

If T is a const-qualified type having at least one data member, it must be a class type with a user-provided default constructor.

Correct me If I am wrong & understood incorrect something.

Destructor
  • 14,123
  • 11
  • 61
  • 126
  • 2
    Are you compiling with optimizations on? Sometimes unused variables will get optimized away that would otherwise not be allowed to compile. – Cory Kramer Jun 15 '15 at 14:20
  • 2
    See [const T{}; works, const T; fails when T is a non-POD,](http://stackoverflow.com/q/29683381/1708801) – Shafik Yaghmour Jun 15 '15 at 14:21

1 Answers1

4

The C++ standard is pretty clear on this, from [dcl.init]:

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.

So gcc is non-compliant in this regard, and cppreference is correct.

Barry
  • 286,269
  • 29
  • 621
  • 977
  • 2
    @meet apparently bug in GCC. BTW Clang [rejects this code](http://coliru.stacked-crooked.com/a/8549d16af658581c). – Anton Savin Jun 15 '15 at 14:27
  • 3
    @meet Because GCC chose not to follow this particular rule. See [bug 57820](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57820) – Barry Jun 15 '15 at 14:27
  • 4
    @meet Or, in short, it is debatable if the standard has a bug in this case, so GCC is going to wait for standardization to decide if this is a screwup before fixing it. – Yakk - Adam Nevraumont Jun 15 '15 at 14:32