[英]Is using reference to pointer that was casted with reinterpret_cast undefined behavior?
Is the following code UB?下面的代码是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.是的,它是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.允许将
void**
reinterpret_cast
为int**
,但隐式取消引用是 UB,因为数据类型 ( void*
) 和它作为 ( int*
) 访问的类型不相似。
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).当
sizeof(void*)
和sizeof(int*)
就不同了(尽管我不知道这是否可能)。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.