AutosarC++17_10-A5.2.3

A cast shall not remove any const or volatile qualification from the type of a pointer or reference

Required inputs: IR

Rationale

Removal of the const or volatile qualification may not meet developer expectations as it may lead to undefined behavior.

Note that either const_cast and traditional C-style casts that remove const or volatile qualification shall not be used.

Example
// $Id: A5-2-3.cpp 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $
#include <cstdint>
void F1(const char *str) noexcept(false) {
  *(const_cast<char *>(str)) =
            ’\0’; // Non-compliant - const qualification removed
}
class C {
public:
  explicit C(std::int32_t) {}
};
void F2() noexcept(false) {
  C const a1 = C(10);
  C *a2 = const_cast<C *>(&a1); // Non-compliant - const qualification removed
  C *a3 = (C *)&a1;             // Non-compliant - const qualification removed
}
extern volatile std::int32_t *F3() noexcept;
void F4() noexcept {
  volatile std::int32_t *ptr1 = F3();
  // ...
  std::int32_t *ptr2 = const_cast<std::int32_t *>(
      ptr1); // Non-compliant - volatile qualification removed
  // ...
  std::int32_t *ptr3 =
      (std::int32_t *)ptr1; // Non-compliant - volatile qualification removed
}
See Also
  • MISRA C++ 2008 [6]: 5-2-5 A cast shall not remove any const or volatile qualification from the type of a pointer or reference.

Possible Messages

Key

Text

Severity

Disabled

cast_removes_atomic

Cast removes _Atomic qualification

None

False

cast_removes_const

Cast removes const qualification

None

False

cast_removes_volatile

Cast removes volatile qualification

None

False

implicit_cast_removes_atomic

Implicit cast removes _Atomic qualification

None

False

implicit_cast_removes_const

Implicit cast removes const qualification

None

False

implicit_cast_removes_volatile

Implicit cast removes volatile qualification

None

False

Options

check_atomic

check_atomic : bool = False

Whether casts affecting _Atomic-qualifiers should be reported
 

check_const

check_const : bool = True

Whether casts affecting const-qualifiers should be reported.
 

check_volatile

check_volatile : bool = True

Whether casts affecting volatile-qualifiers should be reported.
 

only_top_level

only_top_level : bool = False

Whether the check only applies to the top-level pointee or recursively to deeper pointer levels as well.