指针和整数之间的转换

可以使用 reinterpret_cast 将对象指针(包括 void*)或函数指针转换为整数类型。只有在目标类型足够长时才会编译。结果是实现定义的,通常产生指针指向的内存中字节的数字地址。

通常,longunsigned long 足够长以容纳任何指针值,但标准不保证这一点。

Version >= C++ 11

如果存在类型 std::intptr_tstd::uintptr_t,则保证它们足够长以容纳 void*(因此任何指向对象类型的指针)。但是,它们不能保证足够长以容纳函数指针。

类似地,reinterpret_cast 可用于将整数类型转换为指针类型。结果再次是实现定义的,但是通过整数类型的往返保证指针值不变。该标准不保证将零值转换为空指针。

void register_callback(void (*fp)(void*), void* arg); // probably a C API
void my_callback(void* x) {
    std::cout << "the value is: " << reinterpret_cast<long>(x); // will probably compile
}
long x;
std::cin >> x;
register_callback(my_callback,
                  reinterpret_cast<void*>(x)); // hopefully this doesn't lose information...