6

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

Community
  • 1
  • 1
Mihran Hovsepyan
  • 10,810
  • 14
  • 61
  • 111
  • maybe read first here: http://stackoverflow.com/questions/332030/when-should-static-cast-dynamic-cast-and-reinterpret-cast-be-used – jenseb Jul 19 '11 at 11:24

5 Answers5

5

The chain of two static_casts is better - it is less implementation dependent.

Community
  • 1
  • 1
sharptooth
  • 167,383
  • 100
  • 513
  • 979
4

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

SingleNegationElimination
  • 151,563
  • 33
  • 264
  • 304
  • what about this case? Here I have something different than you told, I have a memory pool created this way `new char[size]` and there I'm creating objects of type T via placement operator new, and for determining the place where new object should be created I'm using `some_cast(buffer) + next_object_position` and this **some_cast** is what I'm asking about. – Mihran Hovsepyan Jul 19 '11 at 11:54
2

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

Dave
  • 331
  • 1
  • 4
1

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.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
0

If you really need to do that, reinterpret_cast. It's way more understandable than that static_cast dance.

Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224