This is a draft version of a MISRA C++ 202x rule proposed for public review.
MISRA Rule 8.2.3
Category: Required
Analysis Type: Decidable,Single Translation Unit
Rationale
Using a cast to remove the qualification associated with the addressed type is a violation of the principle of type qualification.
Some of the problems that might arise include:
- Removal of
const
qualification might circumvent the read-only status of an object, which may lead to undefined behaviour;
- Removal of
const
qualification might result in a hardware exception when the object is accessed;
- Removal of
volatile
qualification might result in accesses to an object being removed during optimization.
Example
uint16_t x;
uint16_t * const cpi = &x; // const pointer
uint16_t * const * pcpi; // pointer to const pointer
uint16_t * * ppi;
const uint16_t * pci; // pointer to const
volatile uint16_t * pvi; // pointer to volatile
uint16_t * pi;
pi = cpi; // Rule does not apply - no cast
pi = const_cast< uint16_t * >( pci ); // Non-compliant
pi = const_cast< uint16_t * >( pvi ); // Non-compliant
ppi = const_cast< uint16_t ** >( pcpi ); // Non-compliant
The following examples also violate M23_089: MISRA C++ 2023 Rule 8.2.2.
pi = ( uint16_t * )pci; // Non-compliant
pi = ( uint16_t * )pvi; // Non-compliant
ppi = ( uint16_t ** )pcpi; // Non-compliant
Copyright The MISRA Consortium Limited © 2023