gpt4 book ai didi

c++ - static_cast 和 reinterpret_cast 有什么区别?

转载 作者:IT老高 更新时间:2023-10-28 13:57:54 25 4
gpt4 key购买 nike

Possible Duplicate:
When should static_cast, dynamic_cast and reinterpret_cast be used?

我在 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*intchar,因为这样的转换是有意义的。但是,您不能 static_castint* 转换为 double*,因为这种转换只有在 int* 以某种方式被破坏为指向 double*

reinterpret_cast 是表示不安全转换的转换,它可能将一个值的位重新解释为另一个值的位。例如,使用 reinterpret_castint* 强制转换为 double* 是合法的,尽管结果未指定。类似地,将 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* 的向下转换是明确定义的。

关于c++ - static_cast 和 reinterpret_cast 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6855686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com