Mutable member variables are useful if a class wants to save internal data, and the content is not relevant to the status of the class as seen from the outside (its user).
There are many situations where this makes sense, for example:
- when you do lazy initialization: a resource that needs time to ready is only built when the external user executes a method that really needs it. You could store the resource in a mutable member, so it can be saved from within a
const
method.
- for hashing: imagine a method that does a complicated calculation, and it is known that the result is often needed multiple times for the same input. The method could internally cache the last call's parameters and the result, and if called again with the same parameters, simple reuse them
- debugging and logging information: you could add a counter member that counts how often a
const
method is called, so the counter would be mutable
Generally, whenever a class wants to be able to modify a member from a const
method, it would need to be mutable
. Yes, this could point to a design error - if the changing of the member would bring the class to a different state that is relevant to the outside user, then it would be bad design, as he thinks he didn't change it by calling a const
method. However, if the classes' state change is not relevant for the user, it is good design to make it in mutable
members.