在您开始将其标记为重复之前,我已经阅读了 this但我的问题是关于 MSVS 编译器的。链接的问题讨论了 g++ 编译器。
我在最后更新于 2015 年 11 月 3 日的 MSVS 2015 编译器上尝试了这个程序 here
class Test
{ };
int main()
{ const Test t; }
根据 default initialization上面的程序应该编译失败。它说:
If T is a const-qualified type, it must be a class type with a user-provided default constructor.
因此,在上述程序的情况下需要进行诊断。但是 MSVS 没有给出任何正确的诊断。根据 C++ 标准,MSVS 似乎未在此处确认。 MSVS 中的这个错误是否也像 g++ 中的错误?
最佳答案
根据草案标准 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.
所以你是对的,一个 const
限定的对象必须有一个用户提供的构造函数来初始化。
这是因为 const
限定的对象被初始化一次,如果没有提供默认构造函数,那么该对象将包含未初始化的值。
但是,在您的示例中,class Test
没有成员变量。严格来说,根据标准,格式错误,但没有什么坏处,因为 Test
没有成员变量。
为此,委员会提交了一份缺陷报告 DR 253 .那就是:
If the implicit default constructor initializes all subobjects, no initializer should be required.
GCC 遵循 DR 这就是它编译代码的原因,我的猜测是出于同样的原因 VC++ 也会编译代码。
但是,如果您尝试编译以下代码:
class Test{
int i;
};
int main() {
const Test t;
}
GCC 会报错。 VC++ 2015 将发出诊断信息:
warning C4269: 't': 'const' automatic data initialized with compiler generated default constructor produces unreliable results
关于c++ - 没有用户提供的构造函数的 const 限定类型的默认初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33809441/