Because reinterpret_cast
ignores the type system, it is capable of performing dangerous conversions between unrelated types which can
lead to undefined behavior.
This rule reports an issue for two problematic uses of reinterpret_cast
:
- when it is used to make the compiler believe that an object in memory is from a different type from its real type (for instance, casting a
long*
to double*
, because accessing a long
as if it was a double
is undefined behavior (even if
sizeof(long) == sizeof(double)
),
- when it is used to cast between different levels of a complex inheritance hierarchy (a
static_cast
would apply pointer offsets to
take into account multiple inheritance, for instance, but reinterpret_cast
does not)
Noncompliant code example
class X {};
class Y : virtual X {};
void test() {
long l;
auto a = reinterpret_cast<double&>(l); // Noncompliant: undefined behavior
Y* y;
auto x = reinterpret_cast<X*>(y); // Noncompliant
}