Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reinterpret_cast to the same type

Consider following program:

struct A{};

int main()
{
    A a;
    A b = a;
    A c = reinterpret_cast<A>(a);
}

The compiler(g++14) throws an error about invalid cast from type 'A' to type 'A'. Why is casting to the same type invalid?

like image 645
krawacik3 Avatar asked Oct 17 '19 09:10

krawacik3


People also ask

What does reinterpret_cast mean?

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.

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.

Is reinterpret_cast portable?

Anyway, the consequence of this is, that reinterpret_cast<> is portable as long as you do not rely on the byte order in any way. Your example code does not rely on byte order, it treats all bytes the same (setting them to zero), so that code is portable.

Can reinterpret_cast throw?

No. It is a purely compile-time construct. It is very dangerous, because it lets you get away with very wrong conversions.


2 Answers

It is not allowed, because the standard says so.

There is a rather limited set of allowed conversion that you can do with reinterpret_cast. See eg cppreference. For example the first point listed there is:

1) An expression of integral, enumeration, pointer, or pointer-to-member type can be converted to its own type. The resulting value is the same as the value of expression. (since C++11)

However, casting a custom type (no pointer!) to itself is not on the list. Why would you do that anyhow?

like image 95
463035818_is_not_a_number Avatar answered Sep 23 '22 18:09

463035818_is_not_a_number


Because reinterpret_cast cannot be used for classes and structures, it should be used to reinterpret pointers, references and integral types. It is very well explained in cpp reference

So, in your case one possible valid expression would be reinterpret_cast<A*>(&a)

like image 45
pptaszni Avatar answered Sep 22 '22 18:09

pptaszni