[英]Understanding void* against intptr_t and uintptr_t
This is the code I'm testing: 这是我正在测试的代码:
int value = 0;
void* addyvoid = static_cast<void*>(&value); // C++-style cast.
it works perfectly, but I could use uintptr_t
/ intptr_t
. 它工作得很好,但我可以使用uintptr_t
/ intptr_t
。 But they are not good for holding pointers as people said here because they are too big. 但是,正如人们在这里所说的那样,因为它们太大了,所以它们不适合拿指针。 So, is this true? 那么,这是真的吗? If yes, however, for holding pointers using void*
would be better, but will there be a loss of data? 但是,如果是,使用void*
保持指针会更好,但会丢失数据吗?
The purpose of intptr_t
and uintptr_t
is that in some applications, you actually do need to do some sort of numeric computation on pointer values, perhaps by flipping individual bits, perhaps by XORing them, etc. In those cases, when you need to work with the numeric value of a pointer, intptr_t
and uintptr_t
are integer types that (if they exist) are guaranteed to be large enough to hold any pointer. intptr_t
和uintptr_t
的目的是在某些应用程序中,实际上你需要对指针值进行某种数值计算,可能是通过翻转单个位,也许是通过对它们进行异或运算等。在这些情况下,当你需要使用时指针的数值 , intptr_t
和uintptr_t
是整数类型(如果它们存在)保证足够大以容纳任何指针。 This is not true of, say, int
, since int
's size relative to pointer sizes isn't specified. 例如, int
不是这样,因为未指定int
相对于指针大小的大小。
Because it's fundamentally unsafe to do these conversions, C++ requires that you use reinterpret_cast
to convert to and from intptr_t
and uintptr_t
and pointer types. 因为进行这些转换从根本上说是不安全的,所以C ++要求你使用reinterpret_cast
来转换intptr_t
和uintptr_t
以及指针类型。
If all that you're doing is storing "a pointer to something," and provided that pointer isn't a function pointer or a member function pointer, you can just cast it to void*
. 如果你正在做的就是存储“指向某个东西的指针”,并且只要指针不是函数指针或成员函数指针,你就可以将它转换为void*
。 That cast is guaranteed to work and the conversion from void*
back to the original type only requires a static_cast
and is guaranteed to be safe. 该演员阵容保证有效,从void*
转换回原始类型只需要static_cast
并保证安全。
The size of intptr_t
and uintptr_t
isn't a good reason to avoid them. intptr_t
和uintptr_t
的大小不是避免它们的好理由。 They're just for different applications. 它们仅适用于不同的应用。 If you need to do numeric computations on pointers, use those types. 如果需要对指针进行数值计算,请使用这些类型。 Otherwise, if you just need to store "a pointer to something," use a void*
. 否则,如果您只需要存储“指向某个东西的指针”,请使用void*
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.