It can also be used if inside a getter method (that is usually const), you need to update the stored returned value. As an example, suppose that you have an specific linked-list implementation. For performance issues, you keep the last calculated length of the list, but while returning the length, if the list has been modified, you compute it again, otherwise, you return the last cached value.
class MyLinkedList
{
public:
long getLength() const
{
if (lengthIsModified())
{
mLength = ...; // do the computation here
}
return mLength;
}
private:
mutable long mLength;
};
Warning: It is not that easy to always keep mLength up-to-date because of some specific operations (like merging) in the list.