Rule A5-2-2 (required, implementation, automated)

Traditional C-style casts shall not be used.

Rationale

C-style casts are more dangerous than the C++ named conversion operators. The Cstyle casts are difficult to locate in large programs and the intent of the conversion is not explicit. Traditional C-style casts raise several concerns: C-style casts enable most any type to be converted to most any other type without any 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 the subsequent analysis of the conversion rationale proves difficult for C-style casts Thus, C++ introduces casts (const_cast, dynamic_cast, reinterpret_cast, and static_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);

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

// Compliant - violates another rule

}

See also

MISRA C++ 2008 [7]: 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 [8]: AV Rule 185 C++ style casts (const_cast, reinterpret_cast, and static_cast) shall be used instead of the traditional C-style casts.