了解针对intptr_t和uintptr_t的void * [英] Understanding void* against intptr_t and uintptr_t

查看:539
本文介绍了了解针对intptr_t和uintptr_t的void *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在测试的代码:

This is the code I'm testing:

int value = 0;
void* addyvoid = static_cast<void*>(&value); // C++-style cast.

它工作得很好,但是我可以使用uintptr_t/intptr_t.但是,由于人们在此处所说,它们不适合用来容纳指针,因为它们太大了.那么,这是真的吗?但是,如果可以,使用void*保留指针会更好,但是会丢失数据吗?

it works perfectly, but I could use 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?

推荐答案

intptr_tuintptr_t的目的在于,在某些应用程序中,实际上确实需要对指针值进行某种数值计算,也许通过可能是通过对它们进行异或来进行翻转等.在这种情况下,当您需要使用指针的数字intptr_tuintptr_t是整数类型(如果存在),保证它们足够大以容纳任何指针.例如,int并非如此,因为未指定int相对于指针大小的大小.

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. This is not true of, say, int, since int's size relative to pointer sizes isn't specified.

由于进行这些转换从根本上来说是不安全的,因此C ++要求您使用reinterpret_castintptr_tuintptr_t和指针类型之间进行转换.

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.

如果您要做的只是存储指向某物的指针",并且该指针不是函数指针或成员函数指针,则可以将其强制转换为void*.该强制转换可以正常工作,并且从void*转换回原始类型仅需要static_cast并且可以保证安全.

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*. 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.

intptr_tuintptr_t的大小不是避免使用它们的充分理由.它们仅适用于不同的应用程序.如果需要对指针进行数值计算,请使用这些类型.否则,如果只需要存储指向某物的指针",请使用void*.

The size of intptr_t and uintptr_t isn't a good reason to avoid them. 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*.

这篇关于了解针对intptr_t和uintptr_t的void *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆