问题
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++?
回答1:
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 commity 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
来源:https://stackoverflow.com/questions/33809441/default-initialization-of-const-qualified-type-with-no-user-provided-constructor