AutosarC++17_03-A5.2.4¶
reinterpret_cast shall not be used
Required inputs: IR
| Level | required |
|---|---|
| Target | implementation |
| Enforcement | automated |
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¶
This rule shares the following common options: confidence, exclude_in_macros, exclude_messages_in_system_headers, excludes, extend_exclude_to_macro_invocations, includes, justification_checker, languages, post_processing, provider, report_at, severity
The following places define options that affect this rule: Stylechecks, Analysis-GlobalOptions
allow_cast_of_pointer_sized_integers¶
allow_cast_of_pointer_sized_integers : bool = False
allow_cast_to_type¶
allow_cast_to_type : set[bauhaus.analysis.config.QualifiedName] = set()