8

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)

Robben_Ford_Fan_boy
  • 8,494
  • 11
  • 64
  • 85

3 Answers3

9

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

Edward Strange
  • 40,307
  • 7
  • 73
  • 125
4

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?

Community
  • 1
  • 1
Owen S.
  • 7,665
  • 1
  • 28
  • 44
0

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.

sharptooth
  • 167,383
  • 100
  • 513
  • 979
  • 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 Jun 17 '10 at 19:17
  • 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. – Edward Strange Jun 17 '10 at 19:19
  • @Noah Some reference for this? –  Jun 17 '10 at 19:27
  • 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. – Edward Strange Jun 17 '10 at 19:50
  • @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 Aug 13 '10 at 13:17
  • @Logan Capaldo: Thanks. I was just trying to voice my disagreement with Neil's statement. – Martin York Aug 13 '10 at 15:31