Both static_cast and reinterpret_cast seem to work fine for casting void* to another pointer type. Is there a good reason to favor one over the other?
|
This does actually not describe the effect of a However, this is not what happens in this particular case, where the mapping is well-defined by the standard, namely assigning a type to a typeless pointer without changing its address. This is a reason to prefer Additionally, and arguably more important, is the fact that every use of |
|||||||||||||||||||||
|
|
This is a tough question. On the one hand, Konrad makes an excellent point about the spec definition for reinterpret_cast, although in practice it probably does the same thing. On the other hand, if you're casting between pointer types (as is fairly common when indexing in memory via a char*, for example), static_cast will generate a compiler error and you'll be forced to use reinterpret_cast anyway. In practice I use reinterpret_cast because it's more descriptive of the intent of the cast operation. You could certainly make a case for a different operator to designate pointer reinterprets only (which guaranteed the same address returned), but there isn't one in the standard. |
|||||
|
|
My personal preference is based on code literacy like this:
or
They both do the same in the end, but static_cast seems more appropriate in a middle-ware, app enviroment, while reinterpret cast seems more like something you'd see in a lower-level library IMHO. |
|||||
|
|
I suggest using the weakest possible cast always. reinterpret_cast is may be used to cast a pointer to a float. The more structure-breaking cast is, the more attention using it requires. In case of char*, I'd use c-style cast, until we have some reinterpret_pointer_cast, because it's weaker and nothing else is sufficient. |
|||||||||||||||||||||
|