Search code examples
c++language-lawyerreinterpret-cast

Why is it allowed to reinterpret_cast integral, enumeration and pointer-to-member types to themselves?


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_­cast are listed below. No other conversion can be performed explicitly using reinterpret_­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.

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


Solution

  • It was part of resolving DR 799. The issue was as follows:

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

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

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

    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.