Is the following code UB?
int i = 5;
void *p = &i;
int* &r = reinterpret_cast<int* &>(p);
int* p2 = r;
Please note I do not dereference pointer.
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.
reinterpret_cast is a type of casting operator used in C++. It is used to convert a pointer of some data type into a pointer of another data type, even if the data types before and after conversion are different. It does not check if the pointer type and data pointed by the pointer is same or not.
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.
Yes, it is UB.
reinterpret_cast<int* &>(p);
is equivalent to
*reinterpret_cast<int**>(&p);
reinterpret_cast
of void**
to int**
is allowed, but the implicit dereference is UB because the type of data (void*
) and the type it is being accessed as (int*
) are not similar.
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