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?
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.
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.
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.
No. It is a purely compile-time construct. It is very dangerous, because it lets you get away with very wrong conversions.
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?
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)
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