默认初始化const限定类型,没有用户提供的构造函数 [英] default initialization of const qualified type with no user provided constructor
问题描述
在开始将其标记为重复之前,我已阅读过这,但我的问题是关于MSVS编译器。
我在MSVS 2015编译器上试过这个程序,最后更新于2015年11月3日这里
class Test
{};
int main()
{const Test t; }根据
/ language / default_initializationrel =nofollow> 默认初始化 上述程序在编译时失败。它说:
如果T是一个const限定类型,它必须是一个类型类型
用户提供默认构造函数。
因此,在上述程序的情况下需要诊断。但MSVS没有给出任何适当的诊断。 MSVS似乎在这里根据C ++标准不确认。
根据草案标准 8.5 / p7.3初始化程序[dcl.init] :
(7.3) - 否则,不执行初始化
如果程序调用
const限定类型T的对象的默认初始化,T应该是一个具有用户提供的
默认构造函数的类类型。 p>
所以你是对的,一个 const
提供了要初始化的构造函数。
这是因为 const
- 限定对象初始化一次,默认构造函数,那么对象将包含未初始化的值。
但是,在你的例子 class Test
变量。严格来说,根据标准是不成形的,但没有危害,因为测试
没有成员变量。
为此,该同意书提交了一个缺陷报告 DR 253 < a>。这说明:
如果隐式默认构造函数初始化所有子对象,则不需要
初始化程序。
GCC遵循DR这就是为什么它编译代码,我的猜测是VC ++也编译代码的同样的原因。
但是如果您尝试编译以下代码:
测试{
int i;
};
int main(){
const Test t;
}
GCC将发出错误。 VC ++ 2015将发出诊断:
警告C4269:'t':'const'使用编译器初始化的自动数据
生成默认构造函数产生不可靠的结果
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++?
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
这篇关于默认初始化const限定类型,没有用户提供的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!