c++ - 什么是双关语,它的目的是什么?

标签 c++ casting type-conversion type-punning

Type punning

A form of pointer aliasing where two pointers and refer to the same location in memory but represent that location as different types. The compiler will treat both "puns" as unrelated pointers. Type punning has the potential to cause dependency problems for any data accessed through both pointers.

这篇文章想表达什么? 如果我使用它或不使用它会怎样?

最佳答案

如前所述,类型双关是指您有两个不同类型的指针,它们都指向同一位置。示例:

// BAD CODE
uint32_t data;
uint32_t* u32 = &data;
uint16_t* u16 = (uint16_t*)&data; 
*u16 = ... // de-referencing invokes undefined behavior

此代码调用 C++(和 C)中的未定义行为,因为不允许您通过不兼容类型的指针访问相同的内存位置(有一些特殊异常(exception))。这被非正式地称为“严格的别名违规”,因为它违反了 strict aliasing rule .

另一种进行类型双关的方法是通过 union :

// BAD C++ CODE
typedef union
{
  uint32_t u32;
  uint16_t u16 [2];
} my_type;

my_type mt;
mt.u32 = 1;
std::cout << mt.u16[0]; // access union data through another member, undefined behavior

这也是 C++ 中的未定义行为(但在 C 中允许并且完全没问题)。

关于c++ - 什么是双关语,它的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44137442/

相关文章:

c++ - SSE:从 const __m128 * 转换为 const float *

ios - 如何使用ios将字符串编码为 "windows-1252"?

c++ - Boost::python:对象在重写的方法中自行销毁

c# - 在 C# 中的相似类型之间进行转换

c++ - 如何将字符串传递给 ofstream::open 作为文件名

java - 如何将 int 数组的运算结果转换为 double?

C++ 为模板类/结构设置自己的转换规则

将 INT_MAX 转换为 float ,然后再转换回整数。

c++ - 交换指针: equivalent of `std::unique_ptr::swap`

c++ - 无法创建 GLFW 窗口