I recently learned that the C++ standard contains "strict aliasing rules", which forbid referencing the same memory location via variables of different types.
However, the standard does allows for char
types to legally alias any other type. Does this mean reinterpret_cast
may legally only be used to cast to type char *
or char &
?
I believe strict aliasing allows for casting between types in an inheritance hierarchy, but I think those situations would tend to use dynamic_cast<>?
Thank you
Purpose for using reinterpret_cast It is used when we want to work with bits. If we use this type of cast then it becomes a non-portable product. So, it is suggested not to use this concept unless required. It is only used to typecast any pointer to its original type.
The reinterpret_cast allows the pointer to be treated as an integral type. The result is then bit-shifted and XORed with itself to produce a unique index (unique to a high degree of probability). The index is then truncated by a standard C-style cast to the return type of the function.
the result of a pointer-to-pointer reinterpret_cast operation can't safely be used for anything other than being cast back to the original pointer type.
No. It is a purely compile-time construct. It is very dangerous, because it lets you get away with very wrong conversions.
There are many different uses of reinterpret_cast
. The cppreference page lists 11 different cases.
I guess you are only asking about cases 5 and 6: casting T *
to U *
, and casting T
to U &
.
In those cases, the cast is legal so long as there is not an alignment violation. The strict aliasing issue only arises if you read or write through the resulting expression.
Your summary of the strict aliasing rule in your first paragraph is a great oversimplification, in general there are several legal types for U
. The same cppreference page gives a bulleted list of cases; you can read the exact text of the rule in a C++ standard draft.
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