What is type punning and what is the purpose of it?(什么是类型双关语,它的目的是什么?)
问题描述
双关语
指针别名的一种形式,其中两个指针指向内存中的同一位置,但将该位置表示为不同的类型.编译器将同时处理这两个双关语".作为不相关的指针.对于通过两个指针访问的任何数据,类型双关语都有可能导致依赖性问题.
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.
这篇文章想表达什么?如果我使用或不使用会怎样?
What is this article trying to say? What happens if I use it or not use it?
推荐答案
正如它所说,类型双关是当你有两个不同类型的指针时,都指向同一个位置.示例:
As it says, type punning is when you have two pointers of different type, both pointing at the same location. Example:
// BAD CODE
uint32_t data;
uint32_t* u32 = &data;
uint16_t* u16 = (uint16_t*)&data; // undefined behavior
此代码调用 C++(和 C)中未定义的行为,因为不允许您通过不兼容类型的指针访问相同的内存位置(有一些特殊例外).这被非正式地称为严格的混叠违规".因为它违反了严格别名规则.
This code invokes undefined behavior in C++ (and C) since you aren't allowed to access the same memory location through pointers of non-compatible types (with a few special exceptions). This is informally called a "strict aliasing violation" since it violates the strict aliasing rule.
进行类型双关的另一种方法是通过联合:
Another way of doing type punning is through unions:
// 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 中是允许的并且非常好).
This is also undefined behavior in C++ (but allowed and perfectly fine in C).
这篇关于什么是类型双关语,它的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:什么是类型双关语,它的目的是什么?
基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07