Cast from Void* to TYPE* using C++ style cast: static_cast or reinterpret_cast

雨燕双飞 提交于 2019-12-08 18:35:15

问题


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)


回答1:


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).




回答2:


Use static_cast on both sides for this, and save reinterpret_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?




回答3:


You should always avoid reinterpret_cast, and in this case static_cast will do the job. There is no need for a cast of any sort when converting to a void* pointer.



来源:https://stackoverflow.com/questions/3064509/cast-from-void-to-type-using-c-style-cast-static-cast-or-reinterpret-cast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!