Using C++ mutable Keyword

The keyword mutable is used to allow a particular data member of const object to be modified.

In this interesting post, two examples are given:

class Employee {
public:
    Employee(const std::string & name) 
        : _name(name), _access_count(0) { }
    void set_name(const std::string & name) {
        _name = name;
    }
    std::string get_name() const {
        _access_count++;
        return _name;
    }
    int get_access_count() const { return _access_count; }

private:
    std::string _name;
    mutable int _access_count;
};

As a more complex example, you might want to cache the results of an expensive operation:

class MathObject {
public:
    MathObject() : pi_cached(false) { }
    double pi() const {
        if( ! pi_cached ) {
            /* This is an insanely slow way to calculate pi. */
            pi = 4;
            for(long step = 3; step < 1000000000; step += 4) {
                pi += ((-4.0/(double)step) + (4.0/((double)step+2)));
            }
            pi_cached = true;
        }
        return pi;
    }
private:
    mutable bool pi_cached;
    mutable double pi;
};

Another example is the C++ encapsulation of a blocking queue, which is the intermediate between producers and consumers:

class BlockingQueue {
public:
    bool IsEmpty() const
    {
        MutexLocker locker(m_mutex);
        return m_queue.empty();
    } 
private:
    size_t m_max_elements;
    std::deque<T> m_queue;

    mutable Mutex m_mutex;
    ConditionVariable m_cond_not_empty;
    ConditionVariable m_cond_not_full;
};