C++: Is it safe to cast pointer to int and later back to pointer again?

前端 未结 12 1793
梦如初夏
梦如初夏 2020-11-28 11:38

Is it safe to cast pointer to int and later back to pointer again?

How about if we know if the pointer is 32 bit long and int is 32 bit long?

long* j         


        
12条回答
  •  [愿得一人]
    2020-11-28 12:36

    Yes and no.

    The language specification explicitly states that it is safe (meaning that in the end you will get the original pointer value) as long as the size of the integral type is sufficient to store the [implementation-dependent] integral representation of the pointer.

    So, in general case it is not "safe", since in general case int can easily turn out to be too small. In your specific case it though it might be safe, since your int might be sufficiently large to store your pointer.

    Normally, when you need to do something like that, you should use the intptr_t/uintptr_t types, which are specifically introduced for that purpose. Unfortunately, intptr_t/uintptr_t are not the part of the current C++ standard (they are standard C99 types), but many implementations provide them nevertheless. You can always define these types yourself, of course.

提交回复
热议问题