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

前端 未结 12 1841
梦如初夏
梦如初夏 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

    In general, no; pointers may be larger than int, in which case there's no way to reconstruct the value.

    If an integer type is known to be large enough, then you can; according to the Standard (5.2.10/5):

    A pointer converted to an integer of sufficient size ... and back to the same pointer type will have its original value

    However, in C++03, there's no standard way to tell which integer types are large enough. C++11 and C99 (and hence in practice most C++03 implementations), and also Boost.Integer, define intptr_t and uintptr_t for this purpose. Or you could define your own type and assert (preferably at compile time) that it's large enough; or, if you don't have some special reason for it to be an integer type, use void*.

提交回复
热议问题