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/