c++undefined-behaviorreinterpret-caststrict-aliasing

Examples using reinterpret_cast that do not trigger UB


Reading https://en.cppreference.com/w/cpp/language/reinterpret_cast I wonder what are use-cases of reinterpret_cast that are not UB and are used in practice?

The above description contains many cases where it is legal to convert a pointer to some other type and then back, which is legal. But that seems of less practical use. Accessing an object through a reinterpret_cast pointer is mostly UB due to violations of strict-aliasing (and/or alignment), except accessing through a char*/byte*-pointer.

One helpful exception is casting an integer-constant to a pointer and accessing the target object, which is useful for manipulation of HW-registers (in µC).

Can anyone tell some real use-cases of relevance of reinterpret_cast that are used in practice?


Solution

  • Some examples that come to mind: