可能重复:什么时候应该使用static_cast,dynamic_cast和reinterpret_cast?
我在c中使用c函数,其中在c中作为void类型参数传递的结构直接存储相同的结构类型 .
例如在C.
void getdata(void *data){
Testitem *ti=data;//Testitem is of struct type.
}
在c中使用static_cast:
void foo::getdata(void *data){
Testitem *ti = static_cast<Testitem*>(data);
}
当我使用 reinterpret_cast
时,它执行相同的工作,转换结构
当我使用 Testitem *it=(Testitem *)data;
这也是一样的 . 但是如何通过使用它们中的三个来影响结构 .
1 回答
static_cast
是从一种类型到另一种类型的演员,(直觉上)是一种演员,在某些情况下可以成功并且在没有危险演员的情况下有意义 . 例如,你可以void*
到int*
,因为void*
实际上可能指向int*
,或者int
指向char
,因为这样的转换是有意义的 . 但是,你不能int*
到double*
,因为如果int*
以某种方式被错误地指向double*
,这种转换才有意义 .reinterpret_cast
是一个转换,表示不安全的转换,可能会将一个值的位重新解释为另一个值的位 . 例如,将int*
转换为double*
与reinterpret_cast
是合法的,但结果未指定 . 同样地,将int
转换为void*
与reinterpret_cast
完全合法,尽管它不安全 .static_cast
和reinterpret_cast
都不能从某些东西中移除const
. 你不能使用这些演员之一将const int*
强制转换为int*
. 为此,您将使用const_cast
.形式为
(T)
的C风格演员被定义为尽可能尝试static_cast
,如果不起作用,则返回reinterpret_cast
. 如果绝对必要,它也将适用const_cast
.一般情况下,对于应该安全的演员表,你应该总是更喜欢
static_cast
. 如果您不小心尝试进行定义不明确的强制转换,则编译器将报告错误 . 如果你're doing really is changing the interpretation of some bits in the machine, and only use a C-style cast if you'愿意冒险做reinterpret_cast
,只能使用reinterpret_cast
. 对于您的情况,您应该使用static_cast
,因为void*
中的向下转换在某些情况下是明确定义的 .