本文介绍了什么是punning&它的目的是什么?如果我不使用它会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

指针别名的一种形式,其中两个指针指向内存中的相同位置,但表示该位置为不同类型。编译器将同时处理两个双关。作为不相关的指针。 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.

文章试图说什么?

推荐答案

类型punning是指当您有两个不同类型的指针,它们都指向同一位置时。示例:

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 an perfectly fine in C).

这篇关于什么是punning&amp;它的目的是什么?如果我不使用它会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!