且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2021-10-04 02:58:15

正如它所说,类型双关是当你有两个不同类型的指针时,都指向同一个位置.示例:

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