1

Before you start to mark this as an duplicate I've already read this but my question is about MSVS compiler. The linked question talks about g++ compiler.

I tried this program on MSVS 2015 compiler that is last updated on 3 Nov, 2015 here

class Test
{ };
int main()
{ const Test t; }

according to default initialization the above program should fail in compilation. It says that:

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

So, diagnosis is required in case of above program. But MSVS isn't giving any proper diagnosis. MSVS seems non-confirming here according to C++ standard. Is this bug in MSVS also like as in g++?

Community
  • 1
  • 1
Destructor
  • 14,123
  • 11
  • 61
  • 126
  • 1
    I think I recall reading that some people consider this a defect in the standard, that the code should be valid even if the standard currently says it's not. If I can find a reference I'll make it an answer. –  Nov 19 '15 at 17:08
  • @hvd: waiting for your valuable answer. – Destructor Nov 19 '15 at 17:17
  • It was the same DR 253 that @101010 has found already by now. I'll not post a duplicate answer. :) –  Nov 19 '15 at 18:38

1 Answers1

2

According to the draft standard 8.5/p7.3 Initializers [dcl.init]:

(7.3) — Otherwise, no initialization is performed

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 you're right, a const-qualified object must have a user-provided constructor to be initialized.

This is due to fact that const-qualified objects are initialized once and if no default constructor is provided then the object would contain uninitialized values.

However, in your example class Test has no member variables. Strictly speaking, according to the standard is ill formed, but there's no harm since Test has no member variables.

For this reason the comittee filed a Defect Report DR 253. That says:

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

GCC follows that DR that's why it compiles the code, my guess is that for the same reason VC++ compiles the code as well.

However if you try to compile the following code:

class Test{ 
  int i;
};

int main() { 
  const Test t;
}

GCC will issue an error. VC++ 2015 will emit a diagnostic:

warning C4269: 't': 'const' automatic data initialized with compiler generated default constructor produces unreliable results

Ven
  • 19,015
  • 2
  • 41
  • 61
101010
  • 41,839
  • 11
  • 94
  • 168