首页 文章

static_cast和reinterpret_cast有什么区别? [重复]

提问于
浏览
44

可能重复:什么时候应该使用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 回答

  • 101

    static_cast 是从一种类型到另一种类型的演员,(直觉上)是一种演员,在某些情况下可以成功并且在没有危险演员的情况下有意义 . 例如,你可以 void*int* ,因为 void* 实际上可能指向 int* ,或者 int 指向 char ,因为这样的转换是有意义的 . 但是,你不能 int*double* ,因为如果 int* 以某种方式被错误地指向 double* ,这种转换才有意义 .

    reinterpret_cast 是一个转换,表示不安全的转换,可能会将一个值的位重新解释为另一个值的位 . 例如,将 int* 转换为 double*reinterpret_cast 是合法的,但结果未指定 . 同样地,将 int 转换为 void*reinterpret_cast 完全合法,尽管它不安全 .

    static_castreinterpret_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* 中的向下转换在某些情况下是明确定义的 .

相关问题