static_cast和reinterpret_cast有什么区别

What is the difference between static_cast and reinterpret_cast?

本文关键字:cast 什么 区别 static reinterpret      更新时间:2023-10-16

可能的重复项:
何时应使用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;

这也做了同样的事情。但是使用它们三个如何影响结构。

> static_cast是从一种类型到另一种类型的强制转换,(直观地(是一种在某些情况下可以成功并且在没有危险强制转换的情况下有意义的转换。 例如,你可以static_cast一个void*到一个int*,因为void*实际上可能指向一个int*,或者一个int指向一个char,因为这样的转换是有意义的。 但是,您不能static_cast 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进行应该是安全的铸造。 如果您不小心尝试执行未明确定义的强制转换,则编译器将报告错误。 仅当您正在做的事情确实正在更改机器中某些位的解释时才使用reinterpret_cast,并且仅在您愿意冒险进行reinterpret_cast时才使用 C 样式转换。 在您的情况下,您应该使用 static_cast ,因为在某些情况下,void*的下垂是明确定义的。