Mutable Storage Specifier

What if you wanted to have a const member function which did an expensive calculation and returned the result?

It would be nice to be able to cache this result and avoid recalculation for subsequent calls to the function.

But since it’s a const member function, you can’t store the cached result inside the class, because to do so, you’d have to modify a member variable (thereby violating const).

The mutable storage specifier was added for this reason. A mutable member variable can be modified even by const member functions.

 

C++ C C# Health concepts Leetcode Programming Data Streucture