gpt4 book ai didi

c++ - c-casting to type 反对 c-casting to type's reference

转载 作者:行者123 更新时间:2023-11-30 01:23:53 24 4
gpt4 key购买 nike

在 C++ 中,C 转换为类型或类型的引用有什么区别?

foo = (unsigned int) whatever;  

// Is this the same as:
foo = (unsigned int&) whatever;

最佳答案

不,它甚至完全不同。

(在某些情况下,转换的确切性质取决于 whatever 是什么。我假设 whatever 的类型与 unsigned int 无关。)

引用类型的 C 转换 unsigned int &相当于执行 reinterpret_cast到那种类型

foo = reinterpret_cast<unsigned int &>(whatever);  

根据定义等同于

foo = *reinterpret_cast<unsigned int *>(&whatever);  

whatever在这种情况下必须是左值。

换句话说,转换为引用只是类型双关的另一种方法。你很简单重新解释whatever占用的内存作为unsigned int目的。在一般情况下,行为是未定义的。例如,如果 sizeof whatever小于 unsigned int 的大小,重新解释还将涉及一些甚至不属于whatever的“狂野”内存。 .

同时,非引用 C-cast 只是一个值转换,而不是内存重新解释。对于 unsigned int 的算术转换它相当于static_cast (但如果 whatever 是一个指针,则它等同于 reinterpret_cast )。它读取 whatever并将其转换为 unsigned int根据语言转换规则输入(如果存在转换)。

比如这个

float f = 5;
unsigned int i = (unsigned int) f;

将转换 f输入 unsigned int ,这意味着 i将收到值 5 .同时,如果在你的平台大小unsigned intfloat有相同的大小,那么这个

unsigned int i = (unsigned int &) f;

实际上会重新解释 float 的内部对象表示对象 f具有值(value) 5作为 unsigned int 类型的对象. i 的结果值一般是不可预测的。通常它甚至不会接近 5 (在流行的实现中,您将简单地收到 float 中原始 i 值的 IEE754 表示)。

关于c++ - c-casting to type 反对 c-casting to type's reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14384681/

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