使用 C++ 从 Void* 转换为 TYPE*样式转换: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)
So if your converting from Void* to Type* or from Type* to Void* should you use:
void func(void *p)
{
Params *params = static_cast<Params*>(p);
}
or
void func(void *p)
{
Params *params = reinterpret_cast<Params*>(p);
}
To me static_cast seems the more correct but I've seen both used for the same purpose. Also, does the direction of the conversion matter. i.e. should I still use static_cast for:
_beginthread(func,0,static_cast<void*>(params)
I have read the other questions on C++ style casting but I'm still not sure what the correct way is for this scenario (I think it is static_cast)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该使用 static_cast 以便正确操作指针以指向正确的位置。但是,只有在首先使用静态强制转换将指针强制转换为 void* 时才应该执行此操作。否则,您应该将reinterpret_cast 转换为与原始指针完全相同的类型(无基数等)。
You should use static_cast so that the pointer is correctly manipulated to point at the correct location. However, you should only do this if you used static cast to cast the pointer to void* in the first place. Otherwise you should reinterpret_cast to exactly the same type of the original pointer (no bases or such).
为此,在两侧使用
static_cast
,并在没有其他转换操作执行时保存reinterpret_cast
。以下 SO 主题提供了更多上下文和详细信息:C++ 标准中的哪些措辞允许 static_cast(malloc(N));工作?
什么时候使用reinterpret_cast?
Use
static_cast
on both sides for this, and savereinterpret_cast
for when no other casting operation will do. The following SO topics provide more context and details:What wording in the C++ standard allows static_cast<non-void-type*>(malloc(N)); to work?
When to use reinterpret_cast?
您应该始终避免
reinterpret_cast
,在这种情况下static_cast
就可以完成这项工作。转换为void*
指针时不需要进行任何类型的强制转换。You should always avoid
reinterpret_cast
, and in this casestatic_cast
will do the job. There is no need for a cast of any sort when converting to avoid*
pointer.