AutosarC++18_03-A5.2.2

Traditional C-style casts shall not be used

Required inputs: IR

Rationale

C-style casts are more dangerous than the C++ named conversion operators. The C-style casts are difficult to locate in large programs and the intent of the conversion isnot explicit.

Traditional C-style casts raise several concerns:

  • C-style casts enable most any type to be converted to most any other type withoutany indication of the reason for the conversion
  • C-style cast syntax is difficult to identify for both reviewers and tools. Consequently, both the location of conversion expressions as well as thesubsequent analysis of the conversion rationale proves difficult for C-style casts

Thus, C++ introduces casts (const_cast, dynamic_cast, reinterpret_cast, andstatic_cast) that address these problems. These casts are not only easy to identify,but they also explicitly communicate the developer’s intent for applying a cast.

Example
// $Id: A5-2-2.cpp 289436 2017-10-04 10:45:23Z michal.szczepankiewicz $
#include <cstdint>
class C {
public:
  explicit C(std::int32_t) {}
  virtual void Fn() noexcept {}
};
class D : public C {
public:
  void Fn() noexcept override {}
};
class E {};
std::int32_t G() noexcept { return 7; }
void F() noexcept(false) {
  C a1 = C{10};       // Compliant
  C *a2 = (C *)(&a1); // Non-compliant
  const C a3(5);
  C *a4 = const_cast<C *>(&a3);      // Compliant -    violates another rule
  E *d1 = reinterpret_cast<E *>(a4); // Compliant -      violates another rule
  D *d2 = dynamic_cast<D *>(a2);     // Compliant -    violates another rule
  std::int16_t x1 = 20;
  std::int32_t x2 = static_cast<std::int32_t>(x1); // Compliant
  std::int32_t x3 = (std::int32_t)x1;              // Non-compliant
  std::int32_t x4 = 10;
  float f1 = static_cast<float>(x4);               //   Compliant
  float f2 = (float)x4;                            //   Non-compliant
  std::int32_t x5 = static_cast<std::int32_t>(f1); //   Compliant
  std::int32_t x6 = (std::int32_t)f1;              //   Non-compliant
  (void)G();                                       //   Non-compliant
  static_cast<void>(G());                          //   Compliant
}
See Also
  • MISRA C++ 2008 [6]: 5-2-4 C-style casts (other than void casts) and functional notation casts (other than explicit constructor calls) shall not be used.
  • JSF December 2005 [7]: AV Rule 185 C++ style casts (const_cast, reinterpret_cast, and static_cast) shall be used instead of the traditional C-style casts.

Possible Messages

Key

Text

Severity

Disabled

c_cast

Use of C-style cast in C++ unit.

None

False

Options

allow_void_cast

allow_void_cast : bool = False

If True, (void) is always allowed, else only for return value of calls.
 

allow_void_cast_on_call

allow_void_cast_on_call : bool = False

If True, (void) is allowed, for return value of calls.