25 points · by cdmh · 13y ago · 56 comments
The author also has a rather [confusing article][1] about immutable vs const, that I would discredit personally. He claims that objects accessed via reference to const can modify themselves, which is not true, as you can only access const functions through a const reference.
[1]: http://blog.reliablecpp.com/2013/09/immutable-vs-const/
The example is misleading because there isn't any reason why you would be concerned with such a distinction in this case.
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).
Also, I hope you're not suggesting immutability is a Javaism...
Back then when I graduated (1999), at least in Portugal there were lots and lots of languages to use for assignments, during the degree (5 years long).
I don't mention Java ;)
The problem with strings being mutable by default is that one has to do a lot of defensive copying to avoid unexpected behavior. Mutable strings do have their place, inside a function that's building up a string, before that string is visible to any other part of the program. But it shouldn't be the default.
See also: "The Value of Values" by Rich Hickey (http://www.infoq.com/presentations/Value-Values)