lub*_*bgr 6 c++ language-lawyer reinterpret-cast
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 [...] Conversions that can be performed explicitly using
reinterpret_castare listed below. No other conversion can be performed explicitly usingreinterpret_cast.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)是允许的,而与a相同的演员表struct A{}则不允许。为什么?
这是解决DR 799的一部分。问题如下:
8.2.10 [expr.reinterpret.cast] 第 2 段中的注释说,
根据本节中的限制,可以使用reinterpret_cast 运算符将表达式转换为其自己的类型。
然而,规范文本中没有任何内容允许这种转换,并且第 1 款禁止任何未明确允许的转换。
注释中的想法被认为是有价值的,reinterpret_cast应该允许进行身份转换。所以你问的规范性文本已经添加了。我可以假设对某些基本类型的限制是谨慎的第一步(甚至可能是唯一的步骤)。因为它不会打开与类类型相关的蠕虫罐头,并且不需要调用它们的构造函数。reinterpret_cast一切都是为了不创建新对象,并且可以使用基本类型来做到这一点。不确定这同样适用于类类型。