This defeats the purpose of
std::string const s("Hello"); std::string const s("Hello"); #include <string>
#include <iostream>
// not your code
void innocentF(std::string const& s) {
(const_cast<std::string&>(s)) += std::string(" I'm evil.");
}
// your code
int main() {
std::string const s("hello world.");
innocentF(s);
std::cout << s << std::endl; // hello world. I'm evil.
return 0;
}But what I meant in the above comment is that you can't accidentally type "const_cast". So when you type it, you're on your own. And there is nothing wrong with it in C++ world - if you explicitly state that you want to shoot yourself in the foot, the compiler will just listen to your orders (maybe with some warnings).
7.1.5.1/4: Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.
const_cast is not undefined behavior, but modifying a const object is.