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.
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.
In this absolutely specific case without deferencing it should be okay I think. I verified pointer value. It's different story when sizeof(void*)
and sizeof(int*)
are different (although I do not know whether that is even possible).
By doing this, you are taking complete responsibility of very known scenario .
int i = 5;
void *p = &i; //convert int* => void*
int* &r = reinterpret_cast<int* &>(p); //convert void* which was int* to int*&
int* p2 = r; //**copy** address stays same
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.