c++ - 使用 C++ 样式转换从 Void* 转换为 TYPE*​​ : static_cast or reinterpret_cast

标签 c++ casting static-cast reinterpret-cast

因此,如果您从 Void* 转换为 Type* 或从 Type* 转换为 Void*,您应该使用:

void func(void *p)
{
    Params *params = static_cast<Params*>(p);
}

void func(void *p)
{
    Params *params = reinterpret_cast<Params*>(p);
}

对我来说 static_cast 似乎更正确,但我已经看到两者用于同一目的。此外,转换的方向是否重要。即我是否仍应将 static_cast 用于:

_beginthread(func,0,static_cast<void*>(params)

我已经阅读了关于 C++ 样式转换的其他问题,但我仍然不确定这种情况下正确的方法是什么(我认为它是 static_cast)

最佳答案

您应该使用 static_cast 以便正确操作指针以指向正确的位置。但是,只有在首先使用静态转换将指针转换为 void* 时,才应该这样做。否则,您应该将 reinterpret_cast 转换为与原始指针完全相同的类型(没有基数等)。

关于c++ - 使用 C++ 样式转换从 Void* 转换为 TYPE*​​ : static_cast or reinterpret_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3064509/

相关文章:

c++ - 非常量复制构造函数和返回值的隐式转换

c++ - 什么时候static_casting ceil的结果会妥协?

c++ - 根据情况在 if 语句中声明不同的数据类型 : how to shut up the compiler?

c++ - 在 C++ 中替换集合的最佳方法

c++ - 带有 std::bind 的 std::function<void()> 构造函数

c++ - 为什么这个 Rcpp 代码比字节编译的 R 慢?

java - Struts2 INPUT 结果 : how does it work? 如何处理转换/验证错误?

android - 如何将字符串变量设置为 ImageView 资源?

c# - 枚举整数转换异常可能吗?

c++ - static_cast 限制对公共(public)成员函数的访问?