4 ms·
This defeats the purpose of std::string const s("Hello");
by arithma 13y ago
This defeats the purpose of
std::string const s("Hello");
- ajuc 13y agoYou specify that the place s is const, not the value it keeps. You can still do: #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; }
- zura 13y agoThe point is that one shouldn't do it accidentally. When you're explicitly using const_cast, it is fine.
- zura 13y agoI should clarify that it is fine in a local context, when you know that originally it is a non-const variable. Otherwise, the result is undefined. 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).
- modulus1 13y agoimmutable_string s("hello world."); reinterpret_cast<std::string&>(s) += "I'm evil";
- ajuc 13y ago:) Ok. Right. Nothing's holy in C++.
- vinkelhake 13y agoThat code isn't valid C++. Modifying a const object is undefined behavior. You would have to remove the const on your string in main to make the program well-defined.
- thwest 13y agoconst_cast is undefined behavior? Can you cite the spec?
- vinkelhake 13y agoSure: 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.
- aristidb 13y agoconst_cast is undefined behavior if the actual object is const. If it's a mutable object that just happened to be passed as a reference you can const_cast it. Or that's how I understand it.
- ajuc 13y agoThe funny thing is - it doesn't even show a warning compiled with -Wall.
- alexchamberlain 13y agoWell, the `const_cast` usage is fine, but calling that function on an actual `const` object is not; it's a lot to ask a compiler to warn on that.