static_cast和reinterpret_cast有什么区别
What is the difference between static_cast and reinterpret_cast?
可能的重复项:
何时应使用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_cast
和reinterpret_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*
的下垂是明确定义的。
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 警告处理为错误这里有什么问题
- 什么时候调用组成单元对象的析构函数
- #定义c-预处理器常量..我做错了什么
- 努力将整数转换为链表。不知道我在这里做错了什么
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 什么时候在C++中返回常量引用是个好主意
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- C++避免重复声明的语法是什么
- c++库的公共头文件中应该包含什么
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- ifstream什么都没读
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- "(void) cast"与功能有什么区别 "__attributes__"来沉默未使用的参数警告?
- "Expected '(' for function-style cast or type construction"错误是什么意思?
- 什么类型的Cast从父母到孩子
- 什么类型的cast在这里是合适的
- 在[expr.static.cast]/4中,术语"一个可行函数"指的是什么