3 ms·
> const std::set<int> s // This is immutable. > Foo() : s(helper()) {} // This is a move, not a copy. First, I'll point out that the data of s is not immutab
by humanrebar 9y ago
> const std::set<int> s // This is immutable.
> Foo() : s(helper()) {} // This is a move, not a copy.
First, I'll point out that the data of s is not immutable. The fact that you can const_cast away the const and change the value makes that clear. If people do things like that (or corrupt memory or have race conditions in the code), C++ doesn't necessarily give you clear exceptions or compiler errors. Many of the ways to break things result in "undefined behavior", which might involve data corruption and crashes. I've seen both happen to 'const' objects in production code.
You have a fair point about the move. But not all projects are using C++11 yet. And your use of a 'helper()' builder was actually part of my point as well. The article complained about all the extra code needed in Go to do immutable maps. But it's not true that in C++ you can just add 'const' to a few spots and move on.
I'll also point out that having the 'const' member in 'Foo' likely makes it impossible to implement assignment operators and possibly a move constructor, depending on what you are doing. It's likely if you want to have read-only semantics in your data in C++, you'll have to be aggressive using unique_ptr and shared_ptr so that you can have things like proper move semantics. And that means you'll likely need to be checking for null data.
Point being, you can achieve read-only semantics in C++. But it's not foolproof and it's not as clean as the article seems to imply.
- searealist 9y agoconst std::set<int> s; // This is immutable. const_cast<std::set<int>&>(s).emplace(); // This is UB.
- humanrebar 9y agoAnd what do the assignment operators of Foo look like?
- searealist 9y agoI'm fixing your incorrect understanding of how const works in C++ and you are choosing to be argumentative.
- geezerjay 9y ago> The fact that you can const_cast away No, you cant. The standard states that "any attempt to modify a const object during its lifetime results in undefined behavior". If you're intentionally writing code that relies on undefined behavior, you are intentionally writing broken code.