Practical use of mutable
January 3rd, 2008I have finally found a practical use of mutable keyword in C++
Suppose we have a class and we want to do some "lazy loading":
C++:
class Foo
{
private:
Bar *bar;
public:
const Bar& GetBar() const;
};
{
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;
};
{
private:
mutable Bar *bar;
public:
const Bar& GetBar() const;
};
const Bar& Foo::GetBar() const
{
// lazy loading
if(bar == NULL)
{
bar = new Bar();
}
}
Happy coding ![]()
