Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use a C++ reinterpret_cast over a C-style cast?

I have the following template function used to dump data of any standard type into a binary output stream.

template<typename T> static void
dump ( const T& v, ostream& o ) {
    o.write ( reinterpret_cast<const char*>(&v), sizeof(T));
}

Instead of the reinterpret_cast I could also use a C-style (const char*). Is there any particular reason to use reinterpret_cast? I read a few other posts where reinterpret_cast was frowned upon. But the above usage is legal and cannot be replaced with anything else, right?

like image 950
shekhar Avatar asked Dec 08 '11 06:12

shekhar


2 Answers

There is no difference. In the given situation, the C-style cast is precisely a "reinterpret"-cast.

The reason you should prefer C++-style casts is that they are explicit about what they are casting. A C-style cast will always try to fall back on the crudest possible cast if necessary, while the C++-style cast only compiles if it is possible as intended: a static cast only succeeds if either the values are convertible or the pointers/references are compatible, and a const-cast only works if source and target are cv-qualified versions of one another. A reinterpret-cast states explicitly that you wish to examine an underlying binary representation. (Note that the only valid reinterpret-casts are usually those to void- or char-pointer, unless they're part of some larger trickery.)

like image 166
Kerrek SB Avatar answered Nov 15 '22 21:11

Kerrek SB


C style casting is very very dangerous. So C++ categorical divided the casting to below types based on typical usage,

dynamic_cast(expression) - Allows casting between proper class hierarchic.

const_cast(expression) - Casts away const-ness.

static_cast(expression) - To an extent C style but still respects some incompatibilities between types and do not allow.

reinterpret_cast(expression) - If still the requirement is not met, this is available. C style casting but with a name. So it will be easy to find it in large code base.

Note:- Most "reinterpret_cast" can be eliminated with proper design. In other words "reinterpret_cast" is needed means, most-likely something is wrong in the design.

Update: This should be the last option, and in the case above, the usage is correct. Now mentioning reinterpret_cast will give the reader the impression that intentionally the writer have chosen not to care type safety. But using c style casting will not give that impression.

like image 39
rakesh Avatar answered Nov 15 '22 19:11

rakesh