views:

111

answers:

3

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)

+2  A: 

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

Noah Roberts
+1  A: 

You should always avoid reinterpret_casr, 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.

anon
So why have reinterpret_cast<>? Are there any situations where reinterpre_cast<> should be used. Are can all casting operations be covered by the other 3 cast operators?
Martin York
If the other side of the void* will cast to a base class you need to also cast to that base class before assigning to void.
Noah Roberts
@Noah Some reference for this?
anon
You mean besides the standard? Allowed static casts and their results are described in 5.2.9 (expr.static.cast). The paragraphs about void* are 4 and 10.
Noah Roberts
@MartinYork reinterpret_cast is what you use to go between unrelated types of the same size (eg intptr_t <-> void*, this will not fly with static_cast or similar).
Logan Capaldo
@Logan Capaldo: Thanks. I was just trying to voice my disagreement with Neil's statement.
Martin York
+1  A: 

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:

http://stackoverflow.com/questions/2614392/what-wording-in-the-c-standard-allows-static-castnon-void-typemallocn-t

http://stackoverflow.com/questions/573294/when-to-use-reinterpretcast

Owen S.