没有用户提供的构造函数的 const 限定类型的默认初始化
default initialization of const qualified type with no user provided constructor
在您开始将其标记为重复之前,我已经阅读了 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 初始化器 [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
-qualified 对象被初始化一次,如果没有提供默认构造函数,那么该对象将包含未初始化的值。
但是,在您的示例中 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
在您开始将其标记为重复之前,我已经阅读了 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 初始化器 [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
-qualified 对象被初始化一次,如果没有提供默认构造函数,那么该对象将包含未初始化的值。
但是,在您的示例中 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