从Void *转换为TYPE *使用C ++风格的转换:static_cast或reinterpret_cast [英] Cast from Void* to TYPE* using C++ style cast: static_cast or reinterpret_cast

查看:426
本文介绍了从Void *转换为TYPE *使用C ++风格的转换:static_cast或reinterpret_cast的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,如果你从Void *转换为类型*或从类型*转换为Void *应该使用:

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);
}

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

对我来说static_cast似乎更正确,但我见过都用于同样的目的。此外,转换的方向是否重要。即我应该仍然使用static_cast for:

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)

我已经阅读了关于C ++风格铸造的其他问题,但我仍然不知道什么正确的方式是这方案(我认为它是static_cast)

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)

推荐答案

您应该使用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).

这篇关于从Void *转换为TYPE *使用C ++风格的转换:static_cast或reinterpret_cast的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆