How is cast from char * to T *?

Possible duplicate:
C ++ When we prefer to use two-axis static_cast by reinterpret_cast

What's better?

static_cast<T *>(static_cast<void *>(buffer)); 

or

 reinterpret_cast<T *>(buffer); 

Where buffer is char * (a piece of memory that contains values โ€‹โ€‹of type T ).

+6
source share
5 answers

A chain of two static_cast better - it is less implementation dependent.

+5
source

reinterpret_cast should be used to return an integral type to its original type. If char * was actually originally T * , then reinterpret_cast will do the right thing. If you play other games, you should use static_cast

+4
source

Use reinterpret_cast because this is what you do conceptually. static_cast is used when you expect the compiler to know how to do the conversion. This is a security mechanism because the compiler will generate an error if it really does not know how to do this. Reinterpret_cast is used when you want to say: "Believe me, the bits here are of this type."

+2
source

No one is better, the question is which one is less bad.

static_cast just guaranteed to work if the buffer is really T. You can convert its address to void* and vice versa. If this is some other type, it depends on the implementation, whether it works or not. Alignment problems are just one of the potential problems.

Using reinterpret_cast always implementation dependent. Thus, it does not work better, but at least it makes it obvious that this is not portable code.

So I would use reinterpret_cast here.

+1
source

If you really need to do this, reinterpret_cast . This is more understandable than the static_cast dance.

0
source

Source: https://habr.com/ru/post/893064/


All Articles