gpt4 book ai didi

c++ - C/C++ 编译器如何处理具有不同值范围的类型之间的类型转换?

转载 作者:IT老高 更新时间:2023-10-28 21:37:24 27 4
gpt4 key购买 nike

如何在编译器内不丢失数据的情况下进行类型转换?

例如:

 int i = 10;
UINT k = (UINT) k;

float fl = 10.123;
UINT ufl = (UINT) fl; // data loss here?

char *p = "Stackoverflow Rocks";
unsigned char *up = (unsigned char *) p;

编译器如何处理这种类型转换?一个显示位的低级示例将不胜感激。

最佳答案

首先请注意,强制转换是将一种类型的值转换为另一种类型的值的显式请求。强制转换也总是会产生一个新对象,它是强制转换运算符返回的临时对象。但是,转换为引用类型不会创建新对象。该值引用的对象被重新解释为不同类型的引用。

现在回答你的问题。请注意,有两种主要的转化类型:

  • 促销:可以认为这种类型从可能更窄的类型转换为更宽的类型。从 char 到 int、short 到 int、float 到 double 的转换都是促销。
  • 转换:允许从 long 转换为 int,从 int 转换为 unsigned int 等等。它们原则上会导致信息丢失。例如,如果您将 -1 分配给未签名的类型对象,会发生什么情况是有规则的。在某些情况下,错误的转换可能会导致未定义的行为。如果您分配的 double 大于 float 可以存储的 float,则未定义行为。

让我们看看你的 Actor 阵容:

int i = 10; 
unsigned int k = (unsigned int) i; // :1

float fl = 10.123;
unsigned int ufl = (unsigned int) fl; // :2

char *p = "Stackoverflow Rocks";
unsigned char *up = (unsigned char *) p; // :3
  1. 这种转换会导致转换发生。不会发生数据丢失,因为 10 保证由 unsigned int 存储。如果整数为负数,则该值基本上会环绕 unsigned int 的最大值(参见 4.7/2)。
  2. 10.123 的值被截断为 10。在这里,它确实 导致信息丢失,很明显。由于 10 适合无符号整数,因此定义了行为。
  3. 这实际上需要更多的关注。首先,不推荐使用从字符串文字到 char* 的转换。但是,让我们在这里忽略它。 (见 here)。更重要的是,如果转换为无符号类型会发生什么?实际上,根据 5.2.10/7 未指定其结果(请注意,在这种情况下,该转换的语义与使用 reinterpret_cast 相同,因为这是唯一能够做到这一点的 C++ 转换):

A pointer to an object can be explicitly converted to a pointer to an object of different type. Except that converting an rvalue of type “pointer to T1” to the type "pointer to T2" (where T1 and T2 are object types and where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer value, the result of such a pointer conversion is unspecified.

因此,只有在再次转换回 char * 后才能安全使用指针。

关于c++ - C/C++ 编译器如何处理具有不同值范围的类型之间的类型转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/340413/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com