Although there was a lot of lines written on the topic of reinterpret_cast, and how bad it is, I'm still puzzled with best way to avoid it, especially when dealing with functions like read and write from fstream. So, here is my dilemma...
Let's say we have an integer array that we want to fill with some data from a file.
std::ifstream iFile( ... );
// presume that the type of this array is not a matter of choice
int *a = new int[ 100 ];
We can read with a few different casts:
iFile.read( (char *)a, sizeof( int ) * 100 );
iFile.read( reinterpret_cast< char * >( a ), sizeof( int ) * 100 );
iFile.read( static_cast< char * >( static_cast< void * >( ( a ) ), sizeof( int ) * 100 );
The first one (C-style) is outdated and new style casts we're introduced in C++ for good reasons. The second one is unportable and offers no guarantees. The third one is tedious to write and spoils the fun.
Is there any alternative to this and how should I go about it?
EDIT:
The goal is to achieve code as portable and as standard-conforming as possible.
See Question&Answers more detail:os