为什么允许将自己的整型,枚举和成员指针类型重新解释为_recast_cast? [英] Why is it allowed to reinterpret_cast integral, enumeration and pointer-to-member types to themselves?
问题描述
在最近的问题中,我们看到不允许自己对某些自定义类类型实例进行reinterpret_cast
; struct 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 usingreinterpret_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?