I'm writing some code that uses the fstream read() function and this function expects a char* as the buffer. Later on, I want to work with the bytes in this buffer as unsigned chars, so I'm either going to have to: 1. declare the buffer as a char* and then do static_casts for each element later, 2. declare the buffer as unsigned char* and then do a reinterpret_cast when I pass it to the read function, or 3. declare the buffer as a char* and also create a casted pointer that I use for accessing the buffer as an unsigned char.
Here's a snippet:
char* buf = new char[512];
unsigned char* ubuf = reinterpret_cast<unsigned char*>(buf);
fstream myfile;
myfile.open("foo.img");
myfile.seekg(446);
myfile.read(buf, 16);
//myfile.read(reinterpret_cast<char*>(buf), 16);
int bytes_per_sector = ubuf[1] << 8 | ubuf[0];
...
I like this way because I only have to cast once and I can just access the buffer as either type without doing a cast every time. But, Is this a good practice? Is there anything that can go wrong here? Using reinterpret_cast makes me a little nervous because I don't normally use it and I've been told to be careful with it so many times.
reinterpret_castis actually safe and makes sense. - Konrad Rudolphreinterpret_cast, being more explicit, makes the code more readable as well, since it clearly tells the reader which cast is being performed. - Konrad Rudolphreinterpret_castis explicit and therefore increases readability even if not type safety. Areinterpret_casthas a well-defined meaning. A C-style cast, by contrast, doesn’t. It can mean any of a number of things, so using it in code obscures the actual semantics from the reader. That’s generally acknowledged to be an incredibly bad idea. - Konrad Rudolphimplicit_castisn't in C++14), and make the other 4 kinds (static, const, dynamic, reinterpret) short and concise variants. - Deduplicator