使用哪个投射; static_cast或reinterpret_cast? [英] Which cast to use; static_cast or reinterpret_cast?
问题描述
int i = 1000;
void *p = &i;
int *x = static_cast<int*>(p);
int *y = reinterpret_cast<int*>(p);
这个转换应该用于转换 void *
到 int *
为什么?
which cast should be used to convert from void*
to int*
and why?
推荐答案
static_cast
,只要你知道(通过你的程序的设计),指向的东西真的是一个 int
。
static_cast
provided that you know (by design of your program) that the thing pointed to really is an int
.
static_cast旨在逆转任何隐式转换。您转换为 void *
隐含,因此您可以(并应该)转换回 static_cast
static_cast is designed to reverse any implicit conversion. You converted to void*
implicitly, therefore you can (and should) convert back with static_cast
if you know that you really are just reversing an earlier conversion.
有了这个假设,没有什么被重新解释 - void
是一个不完整的类型,意味着它没有值,所以在任何时候,你解释一个存储的int值void或存储的void value作为int。 void *
只是一个丑陋的说法,我不知道类型,但我要把指针传递给别人谁。
With that assumption, nothing is being reinterpreted - void
is an incomplete type, meaning that it has no values, so at no point are you interpreting either a stored int value "as void" or a stored "void value" as int. void*
is just an ugly way of saying, "I don't know the type, but I'm going to pass the pointer on to someone else who does".
reinterpret_cast
如果您省略了细节,这意味着您可能实际使用类型以外的类型读取内存
reinterpret_cast
if you've omitted details that mean you might actually be reading memory using a type other than the type is was written with, and be aware that your code will have limited portability.
顺便说一句,使用没有很多好的理由, void *
以这种方式在C ++中的指针。 C风格的回调接口通常可以用模板函数(类似于标准函数 qsort
)或虚拟接口(类似于注册监听器的任何东西)替换, 。如果你的C ++代码使用一些C API,当然你没有太多的选择。
By the way, there are not very many good reasons for using a void*
pointer in this way in C++. C-style callback interfaces can often be replaced with either a template function (for anything that resembles the standard function qsort
) or a virtual interface (for anything that resembles a registered listener). If your C++ code is using some C API then of course you don't have much choice.
这篇关于使用哪个投射; static_cast或reinterpret_cast?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!