C++备忘录028:reinterpret_cast与未定义行为

本文探讨了C++中reinterpret_cast的使用及其可能导致的未定义行为。建议开发者谨慎使用,因为不恰当的使用可以引起严重的后果。文章通过例子解释了为什么直接通过reinterpret_cast访问对象的成员可能会导致未定义行为,并提到了C++20中为解决此类问题引入的新特性。同时,讨论了编译器如何通过内存操作优化代码,即使在开启某些特定编译选项时,不同编译器产生的汇编代码也可能相同。
摘要由CSDN通过智能技术生成

首先请务必读完cppreference上reinterpret_cast的描述

能读下来吗?

很难吧

记住了吗?

记不住吧

放心,没有几个人全都记得住的。所以不明白的东西不要用,尽量避免代码中出现reinterpret_cast,因为它引发未定义行为的几率太高了

Whenever an attempt is made to read or modify the stored value of an object of type DynamicType through a glvalue of type AliasedType, the behavior is undefined unless one of the following is true:

  1. AliasedType and DynamicType are similar.
  2. AliasedType is the (possibly cv-qualified) signed or unsigned variant of DynamicType.
  3. AliasedType is std::byte, (since C++17)char, or unsigned char: this permits examination of the object representation of any object as an array of bytes.

常见的数据类型转换中,只有其它类型转成std::bytecharunsigned char才是安全的

简单来说&#

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值