Main Content

AUTOSAR C++14 Rule A5-2-4

reinterpret_cast shall not be used

Description

Rule Definition

reinterpret_cast shall not be used.

Rationale

reinterpret_cast is typically used to explicitly convert between two unrelated data types. For instance, in this example, reinterpret_cast converts the type struct S* to int*:

struct S { int x; } s;
int* ptr = reinterpret_cast<int*> (&s);

However, it is difficult to use reinterpret_cast and not violate type safety. If the result of reinterpret_cast is a pointer, it is safe to dereference the pointer only after you cast the pointer back to its original type.

Polyspace Implementation

The rule checker flags all uses of the reinterpret_cast keyword.

If the rule checker flags an use of reinterpret_cast that you consider safe, add a comment justifying the result. See:

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

class A {
    int x;
    int y;
    public:
      void getxy();
};

class B {
    int z;
    public:
      void getz();
};

void func (B* Bptr) {
    A* Aptr = reinterpret_cast<A*>(Bptr); // Noncompliant
}

The use of reinterpret_cast violates this rule. The result of reinterpret_cast is not safe to dereference since A and B are unrelated classes. Dereferencing Aptr as if it were an A* pointer can result in illegal memory access.

Check Information

Group: Expressions
Category: Required, Automated

Version History

Introduced in R2019a