How cast from char* to T*? [duplicate]
Possible Duplicate:
C++ When should we prefer to use a two chained static_cast over reinterpret_cast
Which is better?
static_cast<T *>(static_cast<void *>(buffer));
or
reinterpret_cast<T *>(buffer);
Where buffer
is char *
(memory chunk which contains values of type T
).
The chain of two static_cast
s is better - it is less implementation dependent.
reinterpret_cast
should be used to cast an integral type back to it's original type. If the char *
really originally was a T *
, then reinterpret_cast
will do the right thing. If you are playing other games, then you should use static_cast
Use reinterpret_cast because that's what you're doing conceptually. static_cast is used when you expect the compiler will know how to do the conversion. It's a safety mechanism because the compiler will generate an error if it doesn't actually know how to do it. Reinterpret_cast is used when you want to say "trust me, the bits here are of this type."
No one is better, the question is which one is less bad.
The static_cast
is just guaranteed to work if the buffer really is a T. You can convert its address to a void*
and back again. If it is of some other type, it is up to the implementation whether it works or not. Alignment issues is but one of the potential problems.
Using a reinterpret_cast
is always implementation dependent. As such, it doesn't work any better, but at least it makes it obvious that this isn't portable code.
Therefore, I would use the reinterpret_cast
here.
If you really need to do that, reinterpret_cast
. It's way more understandable than that static_cast
dance.
精彩评论