When have you used C++ 'mutable' keyword?

Occasionally I use it to mark a mutex or other thread synchronisation primitive as being mutable so that accessors/query methods, which are typically marked const can still lock the mutex.

It's also sometimes useful when you need to instrument your code for debugging or testing purposes, because instrumentation often needs to modify auxiliary data from inside query methods.


I've used mutable in case of object caching results calculated from internal members:

class Transformation
{
    private:
        vec3 translation;
        vec3 scale;
        vec4 rotation;
        mutable mat4 transformation;
        mutable bool changed;
    public:
        Node()
        {
            [...]
            changed = false;
        }
        void set_translation(vec3 _translation)
        {
            translation = _translation;
            changed = true;
        }
        void set_scale(...) ...


        mat4 get_transformation() const
        {
            if(changed)
            {
                 // transformation and changed need to be mutable here
                 transformation = f(translation, scale, rotation); // This take a long time...
                 changed = false;
            }
            return transformation;
        }
};

void apply_tranformation(const Transformation* transfo)
{
    apply(transfo->get_transformation());
}

Google code search reveals a number of uses. For example, in an implementation of XTR cryptography, mutable members are used so that methods can return a reference to a result (preventing copies from being made).

For another example, Webkit uses it to lazily initialize member data (m_lineHeight).

Tags:

C++