mutable
is typically used to allow const
qualified member functions to modify cached data. You can declare getX()
as const
and happily modify x
, that's what mutable is for. However it's generally considered a bad idea to modify the internal state of an object in a member function that by it's declaration says it doesn't.
For example, you have a const member function that calculates a value based on the contents of a container. If the container has a lot of elements it might take a long time to get the result. If the result only changes when you add or remove elements from the container you could cache it for later use. Since the member function is const qualified you would need to declare the result variable as mutable
. Since the result can be calculated from the existing data in the container the cached value isn't considered part of the internal state of the object and it's considered OK to modify it since of a const function.
int Foo::CalcResult() const
{
if(hasValidCache_ == false)
{
// ... recalc value ...
// Cache the result
hasValidCache = true;
cachedValue_ result;
}
return cachedValue_;
}