Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is reinterpret_cast<char *> the only valid use of reinterpret_cast?

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

like image 768
digitale Avatar asked May 12 '16 04:05

digitale


People also ask

When should I use Reinterpret_cast?

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.

What does Reinterpret_cast mean in C++?

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.

Is Reinterpret_cast safe?

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.

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.


1 Answers

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.

like image 144
M.M Avatar answered Oct 20 '22 03:10

M.M