In
C++, one
declares a
data member of a
class to be
mutable to
signify that its
value may be
changed even by
methods or
references which
advertise via
const that they do not
change their
target object. For instance, suppose you had a
class PhoneNumberDatabase with a
method
PhoneNumber lookupNumber(const Person& person) const;
This method is declared const because, semantically speaking, looking up a phone number shouldn't change the database. However, if you wanted to speed up your database by caching the last few numbers looked up, you might think to add a private member
std::vector<PhoneNumber> cached;
As written, this will not work, because lookupNumber, being a const method, cannot write to the cache. The preferred way to solve this problem is to declare cached to be mutable.
(The other preferred way is to write in a language such as Scheme or Objective Caml which relegates assignment to the ghetto where it belongs.)
Gorgonzola points out that, like any construct permitting assignment without mutual exclusion, mutable throws all guarantees of thread safety out the window.