C++新式转型之reinterpret_cast

本文详细介绍了C++中的reinterpret_cast转换,包括指针、引用、函数指针等类型的低级转型。虽然reinterpret_cast允许进行各种类型的转换,但这些转换通常涉及编译器特定的行为,因此使用时需要注意其潜在的不安全性和不确定性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

意图执行低级转型实际动作可能取决于编译器。

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;
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值