Why is this an issue?
Because reinterpret_cast
does not perform any type safety validations, it is capable of performing dangerous conversions between
unrelated types.
Since C++20, a std::bit_cast
should be used instead of reinterpret_cast
to reinterpret a value as being of a different
type of the same length preserving its binary representation, as the behavior of reinterpret_cast
is undefined in such case.
This rule raises an issue when reinterpret_cast
is used.
Noncompliant code example
class A { public: virtual ~A(){} };
class B : public A { public: void doSomething(){} };
void func(A *a, float f) {
if (B* b = reinterpret_cast<B*>(a)) { // Noncompliant
b->doSomething();
}
int x = *reinterpret_cast<int*>(f); // Noncompliant
}
Compliant solution
class A { public: virtual ~A(){} };
class B : public A { public: void doSomething(){} };
void func(A *a, float f) {
if (B* b = dynamic_cast<B*>(a)) {
b->doSomething();
}
int x = std::bit_cast<int>(f);
}
Resources
- CppCoreGuidelines, Type safety profile - Type.1: Don’t use reinterpret_cast.