c++classkeywordmutabledatamember

Does the 'mutable' keyword have any purpose other than allowing a data member to be modified by a const member function?


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.


Solution

  • 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 mutable can be used on a lambda to denote that things captured by value are modifiable (they aren't by default):

    int x = 0;
    auto f1 = [=]() mutable {x = 42;};  // OK
    auto f2 = [=]()         {x = 42;};  // Error: a by-value capture cannot be modified in a non-mutable lambda