1

I have come across mutable variables kind often, yet it seems to me it's always been use to solve a problem of design(typically coping with legacy code) rather than to answer a natural, intrinsic architect design necessity.

Could some architect designer explain when is it really necessary, and why was it introduce in the first place in C++'s language primitive?

Thanks

5

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.

1

@Aganju has given some good examples. I'm just going to add one more, but with a substantial difference. The examples s/he gave were of cases where a class might reasonably consider using a mutable member.

My example is a mutex. Although there are exceptions, as a simple rule of thumb, when a concurrent data structure uses a mutex to protect the stored data, that mutex should usually be mutable.

This has been discussed at various times. For one example, GmanNickG wrote about it in an answer on SO some time ago.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.