简体   繁体   English

将指针强制转换为整数,将该整数递增并进行回退是否安全?

[英]Is it safe to cast pointer to integer, increment that integer, and cast back?

Suppose I have a valid pointer p0 : 假设我有一个有效的指针p0

T a[10];
T* p0 = &a[0];

I know that I can safely round-trip-cast it like this: 我知道我可以像这样安全地往返广播它:

reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(p0)) == p0;

But is it safe to do the following? 但是执行以下操作是否安全?

T* p1 = reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(p0) + sizeof(T));

ie can I be sure that there is no UB and that p1 == &a[1] ? 即我可以确定没有UB且p1 == &a[1]吗?

This is implementation-defined behaviour. 这是实现定义的行为。 Your compiler should document whether or not pointer arithmetic is equivalent to integer arithmetic on the converted numeric values of pointers. 您的编译器应记录指针算术是否等效于指针转换后的数值的整数算术。 That should be the case on modern computers with a "flat" byte-addressed memory space; 在具有“平面”字节寻址内存空间的现代计算机上应该是这种情况。 but it's not guaranteed to work portably on all platforms. 但不能保证它可在所有平台上移植。

Using char* rather than uintptr_t will work portably, as long as you stay within the array and ensure the pointer is correctly aligned for T before converting back. 只要使用char*而不是uintptr_t可以移植,只要您留在数组中并确保指针在返回之前正确对齐T

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM