简体   繁体   中英

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

1. reinterpret_cast means reinterpret the underlying bit pattern. It means explicit conversion in C like:

void *vptr; 
int *iptr = (int *)(vptr);

you should know reinterpret_cast is unsafe, the correctness of conversion decided by yourself.

If you need type-safe conversion, please use static_cast , it means implicit cast or type-safe cast between types. often used between numeric types

2.It may cause truncate, use exact word length int-type is suitable. ie int64_t by include <cstdint>

  1. You should never do it (exceptions where this makes sense are quite rare). Please explain why you need this.
  2. Pointers have fixed size on specific platform.
  3. Standard delivers integer type definition which matches size of pointer o each platform uintptr_t / intptr_t .

I should be using reinterpret_cast ... Is that correct?

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. Reinterpret_cast is preferred because it is more explicit and doesn't allow casting away const.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM