Synopsis: | Prefer static_cast over reinterpret_cast if possible |
Language: | C++ |
Severity Level: | 4 |
Category: | Conversions |
Description: |
A static_cast is a cast from one type to another for which a known method for conversion is available. For example, you can static_cast an int to a char because such a conversion is meaningful. However, you cannot static_cast an int* to a double*, since this conversion only makes sense if the int* has somehow been mangled to point at a double*. A reinterpret_cast is a cast that represents an unsafe conversion that might reinterpret the bits of one value as the bits of another value. For example, casting an int* to a double* is legal with a reinterpret_cast, though the result is unspecified. Similarly, casting an int to a void* is perfectly legal with reinterpret_cast, though it's unsafe. Neither static_cast nor reinterpret_cast can remove const from something. You cannot cast a const int* to an int* using either of these casts. For this, you would use a const_cast. In general, you should always prefer static_cast for casts that should be safe. If you accidentally try doing a cast that isn't well-defined, then the compiler will report an error. Only use reinterpret_cast if what you're doing really is changing the interpretation of some bits in the machine. |
Literature References: |
StackOverflow Q6855686 |