Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 476
lubgr Avatar asked Oct 18 '19 07:10

lubgr


People also ask

What is the purpose of reinterpret_cast and how does it differ from a regular cast?

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.

Is reinterpret_cast safe?

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.

Can reinterpret_cast throw exception?

No. It is a purely compile-time construct.


1 Answers

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.

like image 183
StoryTeller - Unslander Monica Avatar answered Oct 19 '22 03:10

StoryTeller - Unslander Monica