[英]When converting pointers to integers, should I be using reinterpret_cast?
It is my understanding that when converting from a pointer to an integer, I should be using reinterpret_cast because that gives me a compile-time check that the integer variable is large enough to fit a pointer.我的理解是,当从指针转换为整数时,我应该使用 reinterpret_cast,因为这样可以在编译时检查整数变量是否足够大以适合指针。 Is that correct?那是对的吗?
As opposed to just casting where I have no guarantuee and could end up truncating addresses when moving from a 32-bit environment to a 64-bit environment?与只是在我没有保证的情况下进行转换并且在从 32 位环境移动到 64 位环境时最终可能会截断地址不同?
1. reinterpret_cast
means reinterpret the underlying bit pattern. 1. reinterpret_cast
表示重新解释底层位模式。 It means explicit conversion in C like:这意味着 C 中的显式转换,例如:
void *vptr;
int *iptr = (int *)(vptr);
you should know reinterpret_cast is unsafe, the correctness of conversion decided by yourself.你应该知道 reinterpret_cast 是不安全的,转换的正确性由你自己决定。
If you need type-safe conversion, please use static_cast
, it means implicit cast or type-safe cast between types.如果您需要类型安全转换,请使用static_cast
,这意味着类型之间的隐式转换或类型安全转换。 often used between numeric types常用于数值类型之间
2.It may cause truncate, use exact word length int-type is suitable. 2.可能会导致截断,使用精确字长的int类型是合适的。 ie int64_t
by include <cstdint>
即int64_t
包含<cstdint>
I should be using reinterpret_cast ... Is that correct?我应该使用 reinterpret_cast ......这是正确的吗?
Correct... with the precondition that there is a need for such cast in the first place which is rare.正确......前提是首先需要这样的演员,这是罕见的。
.. because that gives me a compile-time check that the integer variable is large enough to fit a pointer. .. 因为这给了我一个编译时检查整数变量是否足够大以适合一个指针。 Is that correct?那是对的吗?
Not correct.不正确。 There is no extra guarantee for warnings when compared to c style cast.与 c 风格转换相比,没有额外的警告保证。 Reinterpret_cast is preferred because it is more explicit and doesn't allow casting away const. Reinterpret_cast 是首选,因为它更明确并且不允许抛弃 const。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.