为什么允许将自己的整型,枚举和成员指针类型重新解释为_recast_cast? [英] Why is it allowed to reinterpret_cast integral, enumeration and pointer-to-member types to themselves?

查看:104
本文介绍了为什么允许将自己的整型,枚举和成员指针类型重新解释为_recast_cast?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近的问题中,我们看到不允许自己对某些自定义类类型实例进行reinterpret_caststruct A{}; reinterpret_cast<A>(A{});是无效的(仅通过引用或指针起作用).这似乎是有道理的,因为缺少现实世界中需要进行身份转换的场景.

In this recent question, we saw that it's not allowed to reinterpret_cast some custom class type instance to itself; struct A{}; reinterpret_cast<A>(A{}); is invalid (it works only through references or pointers). Which seems to make sense, because of the lack of real-world scenarios where such identity conversion is necessary.

检查相应的标准子句,我们在 (重点是我的):

Checking the corresponding standard clause, we have in [expr.reinterpret.cast] (emphasis mine):

1 [...]下面列出了可以使用reinterpret_­cast显式执行的转换. 使用reinterpret_­cast不能显式执行其他任何转换.

1 [...] Conversions that can be performed explicitly using reinterpret_­cast are listed below. No other conversion can be performed explicitly using reinterpret_­cast.

2 [...] 整数,枚举,指针或指针指向成员类型的表达式可以显式转换为其自己的类型;这样的强制转换会产生其操作数的值.

2 [...] An expression of integral, enumeration, pointer, or pointer-to-member type can be explicitly converted to its own type; such a cast yields the value of its operand.

因此,允许使用reinterpret_cast<int>(42),而不允许使用与struct A{}相同的转换.为什么?

So reinterpret_cast<int>(42) is allowed, while the same cast with a struct A{} is not. Why?

推荐答案

这是解决

8.2.10 [expr.reinterpret.cast]第2段中的注释说,

The note in 8.2.10 [expr.reinterpret.cast] paragraph 2 says,

要遵守本节的限制,可以强制转换表达式 使用reinterpret_cast操作符将其设置为自己的类型.

Subject to the restrictions in this section, an expression may be cast to its own type using a reinterpret_cast operator.

但是,规范文本中没有任何内容允许这种转换,并且 第1款禁止任何未明确允许的转换.

However, there is nothing in the normative text that permits this conversion, and paragraph 1 forbids any conversion not explicitly permitted.

笔记中的想法被认为是值得的,应该允许reinterpret_cast进行身份转换.因此,添加了您要求的规范性文本.我可以假设对某些基本类型的限制是一个谨慎的第一步(甚至可能只是一步).由于它无法打开与类类型相关的蠕虫罐,因此需要调用其构造函数. reinterpret_cast是关于不创建新对象的,而可以用基本类型来做到这一点.不确定是否适用于类类型.

The idea in the note was deemed worthwhile, that reinterpret_cast should be allowed to do the identity conversion. So the normative text you ask about was added. I can assume the restriction to some fundamental types is a cautious first (and maybe even only) step. Since it doesn't open the can of worms associated with class types and the need to call their constructors. reinterpret_cast is all about not creating new objects, and one can do that with fundamental types. Not sure the same applies to class types.

这篇关于为什么允许将自己的整型,枚举和成员指针类型重新解释为_recast_cast?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆