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;
}