Practical use of mutable

January 3rd, 2008

I have finally found a practical use of mutable keyword in C++ :D

Suppose we have a class and we want to do some "lazy loading":

C++:
class Foo
{
    private:
        Bar *bar;
    public:
        const Bar& GetBar() const;
};

const Bar& Foo::GetBar() const
{
    // lazy loading
    if(bar == NULL)
    {
        bar = new Bar();
    }
}

Everything would be fine but the const keyword does not allow us to change a value of a bar pointer.
That's the place where mutable is useful :)

C++:
class Foo
{
    private:
        mutable Bar *bar;
    public:
        const Bar& GetBar() const;
};

const Bar& Foo::GetBar() const
{
    // lazy loading
    if(bar == NULL)
    {
        bar = new Bar();
    }
}

Happy coding :)

Designed by SirMike © All rights reserved

Valid XHTML 1.0! Valid CSS!