3 ms·
A const object can still have a const pointer to a non const object. It's a source of much confusion and I've seen such errors often in our own code base. Immu
by injidup 5y ago
A const object can still have a const pointer to a non const object. It's a source of much confusion and I've seen such errors often in our own code base.
Immutability is not so simple in C++ as it might first appear.
- kllrnohj 5y agoA const object can also still have mutable data. const_cast can just remove the 'const' attribute entirely, but even ignoring that "abuse" there's also the 'mutable' keyword which allows fields to be modifiable on const objects. https://en.cppreference.com/w/cpp/language/cv https://en.cppreference.com/w/cpp/language/cv
- zozbot234 5y agoThe rationale for "mutable" is similar to the one for interior mutability in Rust. It's actually really hard to define what it means for something to be "constant" in a systems language, and that's why Rust did not consider deeper sorts of immutability or functional purity.
- fwsgonzo 5y agomutable is used primarily for memoization: https://en.wikipedia.org/wiki/Memoization https://en.wikipedia.org/wiki/Memoization
- hardlianotion 5y agoWe can declare a const pointer to a const object - irritating ceremony but still possible.
- injidup 5y agoNot irritating at all. You are saying that you can't swap the pointed at object for another one AND that you can't change the pointed at object. Two very different things. You have four possible combinations all with different meanings. It's also why I always I insist on putting const to the right of the declaration part the const is referring too. The C++ standard allows const to the left IF it is the first const. But I think this flexibility is kind of garbage....
- hardlianotion 5y agoTrue, but I am a little sensitive to a multiplicity of keywords on a line. Agree about the variable placing being not great. The trouble is most folk use the flexibility to bind the const in the wrong direction, myself included. Then putting it "right" looks "wrong".