What’s wrong with using reinterpret_cast on C++?

Asked

Viewed 53 times

3

I know what to use reinterpret_cast may cause indefinite behavior, but I still don’t understand why (I know it has something to do with the life cycle of the object and alignment of memory). I would like to see some practical example where the cast would result in undefined behavior.

1 answer

0

With it you can convert a pointer of any type to any other type, it is similar to the cast of normal C, the one with (parentheses*).

His main problem(s) is that the compiler has no way of checking if the conversion makes sense. It’s at the developer’s own risk, and it’s very easy to make a mistake.

For example, converting a pointer to integer (int or long int), and then back to pointer, can generate undefined behavior. This works on many architectures, but not all. There are 32-bit architectures with 64-bit pointers, int has 32-bit in 64-bit Linux, and so on.

Converting a char* pointer to double* is undefined behavior. It works on architectures where a double (64-bit or 8-byte) can occupy any memory address, but many architectures make sure that double* points to a multiple of 8. (A correct way to access a double misaligned is to copy it to a local variable using memcpy()and then use the double local variable.)

On some architectures, pointers may have different sizes depending on the type they point to, then you can cake convert from Type* to void* and back to Type*.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.