For a long time I've used reinterpret_cast
like this:
static_assert(sizeof(int) == sizeof(float));
int a = 1;
float b = *reinterpret_cast<float*>(&a); // viewed as float in binary.
However, when I reviewed type conversion in C++ recently, I found that it's UB when the strict aliasing rule is considered! Dereferencing a different type(or to be exact, non-similar type) of pointer to the initial data may be optimized. (I've known that std::bit_cast
in C++20 is an alternative way.)
From my perspective, reinterpret_cast
is mainly used for pointer type conversion. Nevertheless, how can I use another type of pointer considering dereferencing is prohibited?
I've browsed when to use reinterpret_cast, and an answer is quoted below :
One case when reinterpret_cast is necessary is when interfacing with opaque data types. This occurs frequently in vendor APIs over which the programmer has no control. Here's a contrived example where a vendor provides an API for storing and retrieving arbitrary global data.
But when it comes to the implementation of these APIs, if the data should be used there, it's hard to avoid dereferencing the pointer.
It seems that only converting to another pointer type and back to the initial pointer type is reasonable (But what's the point? Why don't you use the initial type or define a template directly?). So my question is: When to use reinterpret_cast
without disobeying that rule? Is there any general usage?
I'm really a novice in C++, so any advice would be appreciated.