A reinterpret_cast operator handles conversions between unrelated types.
With the right angle bracket feature, you may specify a template_id as Type in the reinterpret_cast operator with the >> token in place of two consecutive > tokens. For details, see Class templates (C++ only).
A null pointer value is converted to the null pointer value of the destination type.
Reinterpreting one type of pointer as an incompatible type of pointer is usually invalid. The reinterpret_cast operator, as well as the other named cast operators, is more easily spotted than C-style casts, and highlights the paradox of a strongly typed language that allows explicit casts.
The C++ compiler detects and quietly fixes most but not all violations. It is important to remember that even though a program compiles, its source code may not be completely correct. On some platforms, performance optimizations are predicated on strict adherence to standard aliasing rules. Although the C++ compiler tries to help with type-based aliasing violations, it cannot detect all possible cases.
The following example violates the aliasing rule, but executes as expected when compiled unoptimized in C++ or in K&R C. It also successfully compiles optimized in C++, but does not necessarily execute as expected. The offending line 7 causes an old or uninitialized value for x to be printed.
1 extern int y = 7.;
2
3 int main() {
4 float x;
5 int i;
6 x = y;
7 i = *(int *) &x;
8 printf("i=%d. x=%f.\n", i, x);
9 }
The next code example contains an incorrect cast that the compiler cannot even detect because the cast is across two different files.
1 /* separately compiled file 1 */
2 extern float f;
3 extern int * int_pointer_to_f = (int *) &f; /* suspicious cast */
4
5 /* separately compiled file 2 */
6 extern float f;
7 extern int * int_pointer_to_f;
8 f = 1.0;
9 int i = *int_pointer_to_f; /* no suspicious cast but wrong */
In
line 8, there is no way for the compiler to know that f =
1.0 is storing into the same object that int i =
*int_pointer_to_f is loading from.