digitale digitale - 1 year ago 99
C++ Question

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

types to legally alias any other type. Does this mean
may legally only be used to cast to type
char *
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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download