AutosarC++17_03-A5.2.4

reinterpret_cast shall not be used

Required inputs: IR

Rationale

Use of reinterpret_cast may violate type safety and cause the program to access a variable as if it were of another, unrelated type.

Example
// $Id: A5-2-4.cpp 271696 2017-03-23 09:23:09Z piotr.tanski $
#include <cstdint>
#include <string>
void f1() noexcept {
std::string str = "Hello";
std::int32_t *ptr = reinterpret_cast<std::int32_t *>(&str); // Non-compliant
}
struct A {
std::int32_t x;
std::int32_t y;
};
class B {
public:
virtual ~B() {}

private:
std::int32_t x;
};
class C : public B {};
class D : public B {};
void f2(A *ptr) noexcept {
B *b1 = reinterpret_cast<B *>(ptr); // Non-compliant
std::int32_t num = 0;
A *a1 = reinterpret_cast<A *>(num); // Non-compliant
A *a2 =
(A *)num; // Compliant with this rule, but non-compliant with Rule A5-2-2.
B *b2 = reinterpret_cast<B *>(num); // Non-compliant
D d;
C *c1 = reinterpret_cast<C *>(&d); // Non-compliant - cross cast
C *c2 = (C *)&d; // Compliant with this rule, but non-compliant with Rule
           // A5-2-2. Cross-cast.
B *b3 = &d;      // Compliant - class D is a subclass of class B
}
See Also
  • MISRA C++ 2008 [6]: Rule 5-2-7 An object with pointer type shall not be converted to an unrelated pointer type, either directly or indirectly.
  • C++ Core Guidelines [10]: Type.1: Don’t use reinterpret_cast.

Possible Messages

Key

Text

Severity

Disabled

reinterpret_cast

reinterpret_cast should not be used.

None

False

Options

allow_cast_of_pointer_sized_integers

allow_cast_of_pointer_sized_integers : bool = False

Allow reinterpret_cast to cast to an integer type large enough to represent a pointer value.
 

allow_cast_to_type

allow_cast_to_type : set[bauhaus.analysis.config.QualifiedName] = set()

A set of full qualified type names for those pointer types that reinterpret_cast are allowed to cast to.