...
EXP55-CPP-EX1: An exception to this rule is allowed when it is necessary to cast away const
when invoking a legacy API that does not accept a const
argument, provided the function does not attempt to modify the referenced variable. It is always preferable to modify the API to be const
-correct when possible, however. For example, the following code casts away the const
qualification of INVFNAME
in the call to the audit_log()
function.
Code Block | ||||
---|---|---|---|---|
| ||||
// Legacy function defined elsewhere - cannot be modified; does not attempt to
// modify the contents of the passed parameter.
void audit_log(char *errstr);
void f() {
const char INVFNAME[] = "Invalid file name.";
audit_log(const_cast<char *>(INVFNAME));
}
|
Risk Assessment
If the object is declared as being constant, it may reside in write-protected memory at runtime. Attempting to modify such an object may lead to abnormal program termination or a denial-of-service attack. If an object is declared as being volatile, the compiler can make no assumptions regarding access of that object. Casting away the volatility of an object can result in reads or writes to the object being reordered, or elided entirely, resulting in abnormal program execution.
...