C++ 将指针强制转换为整数、递增该整数并强制转换回是安全的吗?
假设我有一个有效的指针C++ 将指针强制转换为整数、递增该整数并强制转换回是安全的吗?,c++,undefined-behavior,reinterpret-cast,pointer-conversion,C++,Undefined Behavior,Reinterpret Cast,Pointer Conversion,假设我有一个有效的指针p0: T a[10]; T* p0 = &a[0]; 我知道我可以安全地来回投这样的球: reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(p0)) == p0; reinterpret\u cast(reinterpret\u cast(p0))==p0; 但这样做安全吗 T* p1 = reinterpret_cast<T*>(reinterpret_cast<ui
p0
:
T a[10];
T* p0 = &a[0];
我知道我可以安全地来回投这样的球:
reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(p0)) == p0;
reinterpret\u cast(reinterpret\u cast(p0))==p0;
但这样做安全吗
T* p1 = reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(p0) + sizeof(T));
T*p1=reinterpret_cast(reinterpret_cast(p0)+sizeof(T));
i、 e.我是否可以确定没有UB并且
p1==&a[1]
?这是实现定义的行为。编译器应该记录指针算术是否等同于指针转换数值上的整数算术。在具有“扁平”字节寻址存储空间的现代计算机上应该是这样;但它并不能保证在所有平台上都可以移植
使用
char*
而不是uintpttr\u t
将可移植工作,只要您留在数组中,并确保在转换回数组之前指针正确对齐t
。您所说的“我可以确保没有未签名的字节”是什么意思?哪里?@ TV0ID UB是C++世界中一个流行的用于未定义行为的缩写词。我确信在Word寻址系统中会失败,其中通过“代码> N< /代码>递增地址使其指向代码< N*WordSuth字节。@ TeV0ID:未定义的行为,而不是未签名的字节。重复: