A while ago, I came across some code that marked a data member of a class with the mutable keyword. As far as I can see it simply allows you to modify a member in a const-qualified member method:
class Foo { private: mutable bool done_; public: void doSomething() const { ...; done_ = true; } };
Is this the only use of this keyword, or is there more to it than meets the eye? I have since used this technique in a class, marking a boost::mutex as mutable, allowing const functions to lock it for thread-safety reasons, but, to be honest, it feels like a bit of a hack.
It allows the differentiation of bitwise const and logical const. Logical const is when an object doesn’t change in a way that is visible through the public interface, like your locking example. Another example would be a class that computes a value the first time it is requested, and caches the result.
Since c++11
mutablecan be used on a lambda to denote that things captured by value are modifiable (they aren’t by default):