提问人:HeretoLearn 提问时间:2/22/2009 最后编辑:SisirHeretoLearn 更新时间:4/7/2023 访问量:473596
何时使用reinterpret_cast?
When to use reinterpret_cast?
问:
我对 vs 的适用性有点困惑。从我所读到的内容来看,一般规则是当类型可以在编译时解释时使用静态强制转换,因此这个词.这也是 C++ 编译器在内部用于隐式强制转换的强制转换。reinterpret_cast
static_cast
static
reinterpret_cast
s 适用于两种场景:
- 将整数类型转换为指针类型,反之亦然
- 将一种指针类型转换为另一种指针类型。我得到的一般想法是这是不可移植的,应该避免。
我有点困惑的地方是我需要的一个用法,我从 C 调用 C++,C 代码需要保留 C++ 对象,所以基本上它包含一个 .应该使用什么强制转换来转换 和 Class 类型?void*
void *
我见过两者的用法 和 ?虽然从我一直在阅读的内容来看,它似乎更好,因为投射可以在编译时发生?虽然它说用于从一种指针类型转换为另一种指针类型?static_cast
reinterpret_cast
static
reinterpret_cast
答:
阅读常见问题解答!在 C 中保存 C++ 数据可能会有风险。
在 C++ 中,指向对象的指针可以在没有任何强制转换的情况下转换为。但反过来就不是这样了。您需要一个来取回原始指针。void *
static_cast
的含义不是由 C++ 标准定义的。因此,从理论上讲,可能会使您的程序崩溃。在实践中,编译器会尝试执行您期望的操作,即将您传入的内容的位解释为,就好像它们是您要强制转换为的类型一样。如果你知道你要使用的编译器做什么,你就可以使用它,但说它是可移植的就是撒谎。reinterpret_cast
reinterpret_cast
reinterpret_cast
对于您描述的情况,以及您可能考虑的几乎任何情况,您可以使用或其他一些替代方法。除其他事项外,该标准还说明了您可以期待的内容 (§5.2.9):reinterpret_cast
static_cast
static_cast
“指向 cv void 的指针”类型的右值可以显式转换为指向对象类型的指针。指向对象的指针类型的值转换为“指向 cv void 的指针”并返回到原始指针类型将具有其原始值。
因此,对于您的用例,似乎很清楚标准化委员会打算让您使用 .static_cast
评论
reinterpret_crash
template<class T, U> T reinterpret_crash(U a) { return *(T*)nullptr; }
C++ 标准保证以下几点:
static_cast
对指向和从的指针进行操作会保留地址。也就是说,在以下 中,和 都指向同一个地址:void*
a
b
c
int* a = new int();
void* b = static_cast<void*>(a);
int* c = static_cast<int*>(b);
reinterpret_cast
仅保证如果将指针强制转换为其他类型,然后将其reinterpret_cast
回原始类型,则将获得原始值。所以在下文中:
int* a = new int();
void* b = reinterpret_cast<void*>(a);
int* c = reinterpret_cast<int*>(b);
a
并包含相同的值,但 的值未指定。(在实践中,它通常包含与 和 相同的地址,但标准中没有指定,并且在具有更复杂内存系统的计算机上可能并非如此。c
b
a
c
对于来回的铸造,应优先选择。void*
static_cast
评论
b
reinterpret_cast
int*
void*
reinterpret_cast
一种情况是与不透明数据类型交互时。这在程序员无法控制的供应商 API 中经常发生。下面是一个人为的示例,其中供应商提供了一个用于存储和检索任意全局数据的 API:reinterpret_cast
// vendor.hpp
typedef struct _Opaque * VendorGlobalUserData;
void VendorSetUserData(VendorGlobalUserData p);
VendorGlobalUserData VendorGetUserData();
要使用此 API,程序员必须将其数据转换回并返回。 行不通,必须使用:VendorGlobalUserData
static_cast
reinterpret_cast
// main.cpp
#include "vendor.hpp"
#include <iostream>
using namespace std;
struct MyUserData {
MyUserData() : m(42) {}
int m;
};
int main() {
MyUserData u;
// store global data
VendorGlobalUserData d1;
// d1 = &u; // compile error
// d1 = static_cast<VendorGlobalUserData>(&u); // compile error
d1 = reinterpret_cast<VendorGlobalUserData>(&u); // ok
VendorSetUserData(d1);
// do other stuff...
// retrieve global data
VendorGlobalUserData d2 = VendorGetUserData();
MyUserData * p = 0;
// p = d2; // compile error
// p = static_cast<MyUserData *>(d2); // compile error
p = reinterpret_cast<MyUserData *>(d2); // ok
if (p) { cout << p->m << endl; }
return 0;
}
下面是示例 API 的人工实现:
// vendor.cpp
static VendorGlobalUserData g = 0;
void VendorSetUserData(VendorGlobalUserData p) { g = p; }
VendorGlobalUserData VendorGetUserData() { return g; }
评论
void*
USpoofChecker*
USpoofChecker
USpoofChecker*
reinterpret_cast
struct_a*->void*->struct_a*
struct_a*->void*->struct_b*
atruct_a->struct_b*
template <class outType, class inType>
outType safe_cast(inType pointer)
{
void* temp = static_cast<void*>(pointer);
return static_cast<outType>(temp);
}
我试图得出结论,并使用模板编写了一个简单的安全投射。 请注意,此解决方案不保证在函数上强制转换指针。
评论
reinterpret_cast
v
T
static_cast<cv T*>(static_cast<cv void*>(v))
c++2003
reinterpret_cast
static_cast<cv T*>(static_cast<cv void*>(v))
C++03
C++98
reinterpret_cast
可以使用reinterprete_cast在编译时检查继承。
请看这里:在编译时使用 reinterpret_cast 检查继承
reinterpret_cast的一个用途是,如果要对 (IEEE 754) 浮点数应用按位运算。这方面的一个例子是快速平方根反比技巧:
https://en.wikipedia.org/wiki/Fast_inverse_square_root#Overview_of_the_code
它将浮点数的二进制表示视为整数,将其向右移动并从常数中减去,从而将指数减半和否定。转换回浮点数后,它会经过牛顿-拉夫森迭代,以使这个近似值更精确:
float Q_rsqrt( float number )
{
long i;
float x2, y;
const float threehalfs = 1.5F;
x2 = number * 0.5F;
y = number;
i = * ( long * ) &y; // evil floating point bit level hacking
i = 0x5f3759df - ( i >> 1 ); // what the deuce?
y = * ( float * ) &i;
y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
return y;
}
这最初是用 C 语言编写的,因此使用 C 强制转换,但类似的 C++强制转换是reinterpret_cast。
评论
error: invalid cast of an rvalue expression of type 'int64_t {aka long long int}' to type 'double&' reinterpret_cast<double&>((reinterpret_cast<int64_t&>(d) >> 1) + (1L << 61))
- ideone.com/6S4ijc
reinterpret_cast
memcpy
memcpy
快速回答:如果它编译,请使用,否则求助于 .static_cast
reinterpret_cast
首先,这里有一些特定类型的数据,例如 int:
int x = 0x7fffffff://==nan in binary representation
然后,您希望访问与其他类型(如 float)相同的变量: 您可以在以下两者之间做出决定
float y = reinterpret_cast<float&>(x);
//this could only be used in cpp, looks like a function with template-parameters
或
float y = *(float*)&(x);
//this could be used in c and cpp
简介:这意味着相同的内存被用作不同的类型。因此,您可以将浮点数的二进制表示形式转换为如上所述的 int 类型为浮点数。例如,0x80000000 是 -0(尾数和指数为 null,但符号 msb 为 1)。这也适用于双打和长双打。
优化:我认为reinterpret_cast会在许多编译器中进行优化,而 c 转换是通过指针算法进行的(该值必须复制到内存中,因为指针无法指向 cpu- 寄存器)。
注意:在这两种情况下,您都应该在强制转换之前将强制转换值保存在变量中!此宏可能会有所帮助:
#define asvar(x) ({decltype(x) __tmp__ = (x); __tmp__; })
评论
reinterpret_cast
int
float&
memcpy
简短的回答:如果您不知道代表什么,请不要使用它。如果你将来需要它,你会知道的。reinterpret_cast
完整答案:
让我们考虑一下基本的数字类型。
例如,当您转换为处理器时,需要调用一些计算,因为两个数字具有不同的位表示形式。这就是static_cast
所代表的。int(12)
float (12.0f)
另一方面,当您调用 reinterpret_cast
时,CPU 不会调用任何计算。它只是将内存中的一组位视为具有另一种类型。因此,当您转换为使用此关键字时,新值(在指针取消引用之后)在数学意义上与旧值无关(忽略读取此值是未定义行为的事实)。int*
float*
请注意,在reinterprt_cast后读取或修改值通常是未定义的行为。在大多数情况下,如果要实现某些数据的位表示,则应使用指针或引用(从 C++17 开始),这几乎总是合法的操作。其他“安全”类型是 和 ,但我想说它不应该在现代 C++ 中用于此目的,因为它具有更好的语义。std::byte
char
unsigned char
std::byte
例:确实,由于一个原因 - 字节顺序(字节序)。但这往往是令人惊讶地使用它的最佳理由。让我们想象一下这个例子:你必须从文件中读取二进制 32 位数字,并且你知道它是大端序。您的代码必须是通用的,并且必须在大端(例如某些 ARM)和小端(例如 x86)系统上正常工作。所以你必须检查字节顺序。它在编译时是众所周知的,因此您可以编写 你可以编写一个函数来实现这一点:constexpr
函数:reinterpret_cast
/*constexpr*/ bool is_little_endian() {
std::uint16_t x=0x0001;
auto p = reinterpret_cast<std::uint8_t*>(&x);
return *p != 0;
}
解释:内存中的二进制表示可以是 (big) 或 (little endian)。重新解释转换后,指针下的字节可以分别是 或 。如果使用 static-casting,则无论使用什么字节序,它都将始终为 。x
0000'0000'0000'0001
0000'0001'0000'0000
p
0000'0000
0000'0001
0000'0001
编辑:
在第一个版本中,我将示例函数is_little_endian
为 constexpr
。它在最新的 gcc (8.3.0) 上编译良好,但标准说它是非法的。clang 编译器拒绝编译它(这是正确的)。
评论
short
这是 Avi Ginsburg 程序的一个变体,它清楚地说明了 Chris Luengo、flodin 和 cmdLP 提到的属性:编译器将指向的内存位置视为新类型的对象:reinterpret_cast
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class A
{
public:
int i;
};
class B : public A
{
public:
virtual void f() {}
};
int main()
{
string s;
B b;
b.i = 0;
A* as = static_cast<A*>(&b);
A* ar = reinterpret_cast<A*>(&b);
B* c = reinterpret_cast<B*>(ar);
cout << "as->i = " << hex << setfill('0') << as->i << "\n";
cout << "ar->i = " << ar->i << "\n";
cout << "b.i = " << b.i << "\n";
cout << "c->i = " << c->i << "\n";
cout << "\n";
cout << "&(as->i) = " << &(as->i) << "\n";
cout << "&(ar->i) = " << &(ar->i) << "\n";
cout << "&(b.i) = " << &(b.i) << "\n";
cout << "&(c->i) = " << &(c->i) << "\n";
cout << "\n";
cout << "&b = " << &b << "\n";
cout << "as = " << as << "\n";
cout << "ar = " << ar << "\n";
cout << "c = " << c << "\n";
cout << "Press ENTER to exit.\n";
getline(cin,s);
}
结果如下:
as->i = 0
ar->i = 50ee64
b.i = 0
c->i = 0
&(as->i) = 00EFF978
&(ar->i) = 00EFF974
&(b.i) = 00EFF978
&(c->i) = 00EFF978
&b = 00EFF974
as = 00EFF978
ar = 00EFF974
c = 00EFF974
Press ENTER to exit.
可以看出,首先将 B 对象作为特定于 B 的数据构建在内存中,然后是嵌入的 A 对象。正确地返回嵌入的 A 对象的地址,由 创建的指针正确地给出数据字段的值。生成的指针将 的内存位置视为一个普通的 A 对象,因此当指针尝试获取数据字段时,它会返回一些特定于 B 的数据,就好像它是该字段的内容一样。static_cast
static_cast
reinterpret_cast
b
的一种用途是将指针转换为无符号整数(当指针和无符号整数的大小相同时):reinterpret_cast
int i;
unsigned int u = reinterpret_cast<unsigned int>(&i);
评论
上一个:在 PHP 中将整数转换为字符串
下一个:如何显示 widememo 列?
评论
reinterpret_cast
在运行时不会发生。它们都是编译时语句。来自 en.cppreference.com/w/cpp/language/reinterpret_cast:“与 static_cast 不同,但与 const_cast 不同,reinterpret_cast表达式不会编译为任何 CPU 指令。它纯粹是一个编译器指令,它指示编译器将表达式的位序列(对象表示)视为具有 new_type 类型。