Why is this an issue?
Using const
in your code improves reliability and maintenance. When passing a const
value, developers assume that its
value won’t be changed. But using const_cast<>()
to cast away a const
qualifier, destroys developer assumptions and
code reliability. It is a bad practice and reveals a flaw in the design. Furthermore, it may have an undefined behavior.
Noncompliant code example
User& func(const int& value, const User& user) {
const_cast<int&>(value) = 2; // Noncompliant and undefined behavior
return const_cast<User&>(user); // Noncompliant
}
Compliant solution
User& func(int& value, User& user) {
value = 2;
return user;
}
Resources
- MISRA C:2004, 11.5 - A cast shall not be performed that removes any const or volatile qualification from the type addressed by a pointer
- MISRA C++:2008, 5-2-5 - A cast shall not remove any const or volatile qualification from the type of a pointer or reference
- MISRA C:2012, 11.8 - A cast shall not remove any const or volatile qualification from the type pointed to by a pointer
- CERT, EXP32-C. - Do not access a volatile object through a nonvolatile reference
- CERT, EXP05-C. - Do not cast away a const qualification
- CERT, EXP55-CPP. - Do not access a cv-qualified object through a cv-unqualified type
- C++ Core Guidelines Type.3 - Don’t use const_cast to cast away const (i.e., at all): Don’t cast away const.