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 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.
So reinterpret_cast<int>(42)
is allowed, while the same cast with a struct A{}
is not. Why?
reinterpret_cast is a type of casting operator used in C++. It is used to convert a pointer of some data type into a pointer of another data type, even if the data types before and after conversion are different. It does not check if the pointer type and data pointed by the pointer is same or not.
The result of a reinterpret_cast cannot safely be used for anything other than being cast back to its original type. Other uses are, at best, nonportable. The reinterpret_cast operator cannot cast away the const , volatile , or __unaligned attributes.
No. It is a purely compile-time construct.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With