意图执行低级转型实际动作可能取决于编译器。
reinterpret_cast<new_type>(expression);
这是一个完全的编译器行为,它将expression的二进制序列解释成new_type。正因为他是从二进制的角度做转型,所以他可以“随便搞”,但也比较危险。
1) An expression of integral, enumeration, pointer, or pointer-to-member type can be converted to its own type. The resulting value is the same as the value of expression. (since C++11)
同类型转换将保持同样的值:
#include <iostream>
using namespace std;
int main()
{
int a=10;
int b=reinterpret_cast<int>(a);
cout<<b<<endl;
return 0;
}
2) Any pointer can be converted to any integral type large enough to hold the value of the pointer (e.g. to std::uintptr_t)
指针类型可以转换成整型,前提是有足够的空间来保存。
3) A value of any integral or enumeration type can be converted to a pointer type. A pointer converted to an integer of sufficient size and back to the same pointer type is guaranteed to have its original value, otherwise the resulting pointer cannot be dereferenced safely (the round-trip conversion in the opposite direction is not guaranteed; the same pointer may have multiple integer representations) The null pointer constant NULL or integer zero is not guaranteed to yield the null pointer value of the target type; static_cast or implicit conversion should be used for this purpose.
值类型也可以转成指针类型,并且能够保证指针类型指向的地址将有原来的值,不过这种转型是不安全的。
下面是2、3两条的例子
int main()
{
int a = 10;
int *pa = &a;
unsigned long b = reinterpret_cast<unsigned long>(pa);
cout <<std::hex<< b << endl;