This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 8.2.5 - reinterpret_cast shall not be used
[basic.types] / 2
[basic.compound] / 4
[expr.reinterpret.cast]
Category: Required
Analysis: Decidable,Single Translation Unit
Rationale
Casting between unrelated types generally results in undefined behaviour.
Exception
The following are allowed by exception as the behaviour is well defined:
- Using
reinterpret_cast< T * > to cast any object pointer to a pointer to T, where T is one of
void, char, unsigned char or std::byte, possibly cv-qualified.
- Using
reinterpret_cast< T >( p ) to convert a pointer p to an integer of type T that is large
enough to represent a pointer value (e.g. std::uintptr_t).
Example
uint8_t * p1;
uint32_t * p2;
p2 = reinterpret_cast< uint32_t * >( p1 ); // Non-compliant
extern uint32_t read_value();
extern void print( uint32_t n );
void f()
{
uint32_t u = read_value();
uint16_t * p3 = reinterpret_cast< uint16_t * >( &u ); // Non-compliant
}
void g()
{
std::array< int32_t, 2 > a{};
auto p4 = reinterpret_cast< int32_t(*)[ 2 ]>( a.data() ); // Non-compliant
( *p4 )[ 0 ] = 42; // Undefined behaviour
}
In the following example, the target type uint64_t used in the initializer for p7 violates M23_369: MISRA C++
2023 Rule 8.2.8.
void h( float x )
{
auto p5 = reinterpret_cast< std::byte const * >( &x ); // Compliant by exception
auto p6 = reinterpret_cast< std::uintptr_t >( &x ); // Compliant by exception
auto p7 = reinterpret_cast< uint64_t >( &x ); // Compliant by exception
}
Copyright The MISRA Consortium Limited © 2023