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

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

这篇关于什么是类型双关语,它的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:什么是类型双关语,它的目的是什么?

基础教程推荐