When have you used C++ 'mutable' keyword? [closed]

When have you used C++ mutable keyword? and why? I don't think I have ever had to use that keyword. I understand it is used for things such as caching (or perhaps memorization) but in what class and condition have you ever needed to use it in?


Solution 1:

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.

Solution 2:

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());
}

Solution 3:

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).

Solution 4:

I use mutable for class members that are initialized on demand, especially from a database or source external to the program. This allows the "getter" functions to create the object on demand otherwise it is a constant method.

Solution 5:

I use it when locking a mutex for thread-safety. The mutex is marked as mutable so the methods that lock it can remain const.