什么是类型双关语,它的目的是什么?

2022-01-13 00:00:00 type-conversion casting c++ 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.

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

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).

相关文章