The reinterpret_cast operator (C++ only)

A reinterpret_cast operator handles conversions between unrelated types.

Read syntax diagramSkip visual syntax diagramreinterpret_cast operator syntax
 
>>-reinterpret_cast--<--Type-->--(--expression--)--------------><
 

The reinterpret_cast operator produces a value of a new type that has the same bit pattern as its argument. You cannot cast away a const or volatile qualification. You can explicitly perform the following conversions:

A null pointer value is converted to the null pointer value of the destination type.

Given an lvalue expression of type T and an object x, the following two conversions are synonymous:

C++ also supports C-style casts. The two styles of explicit casts have different syntax but the same semantics, and either way of 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 will execute as expected when compiled unoptimized in C++ or in K&R C. It will also successfully compile optimized in C++, but will 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.

Related information



[ Top of Page | Previous Page | Next Page | Contents | Index ]