intptr_t 有什么用?

2021-12-13 00:00:00 pointers c c++

我知道它是一个整数类型,可以在不丢失数据的情况下转换为/从指针转换,但我为什么要这样做呢?与 void* 用于保存指针和 THE_REAL_TYPE*?? 用于指针运算相比,整数类型有什么优势?

I know it is an integer type that can be cast to/from pointer without loss of data, but why would I ever want to do this? What advantage does having an integer type have over void* for holding the pointer and THE_REAL_TYPE* for pointer arithmetic?

编辑
标记为已经被问过"的问题不回答这个.问题是使用 intptr_t 作为 void* 的一般替代品是否是一个好主意,并且那里的答案似乎是不要使用 intptr_t",所以我的问题仍然有效:intptr_t 的一个好的用例是什么?

EDIT
The question marked as "already been asked" doesn't answer this. The question there is if using intptr_t as a general replacement for void* is a good idea, and the answers there seem to be "don't use intptr_t", so my question is still valid: What would be a good use case for intptr_t?

推荐答案

主要原因,你不能对 void * 进行按位运算,但你可以对 intptr_t 做同样的操作.

The primary reason, you cannot do bitwise operation on a void *, but you can do the same on a intptr_t.

在许多需要对地址执行按位运算的场合,可以使用intptr_t.

On many occassion, where you need to perform bitwise operation on an address, you can use intptr_t.

然而,对于按位运算,最好的方法是使用 unsigned 对应物,uintptr_t.

However, for bitwise operations, best approach is to use the unsigned counterpart, uintptr_t.

如 其他答案中所述,@chux,指针比较是另一个重要方面.

As mentioned in the other answer by @chux, pointer comparison is another important aspect.

此外,FWIW,根据 C11 标准,§7.20.1.4,

Also, FWIW, as per C11 standard, §7.20.1.4,

这些类型是可选的.

相关文章