The mutable storage specifier denotes a data member that is never const, even if its object is const-qualified. As such, mutable members are particularly useful for hiding implementation details from a client that calls a const member function.
const member functions do not change the state of their object. However, in some cases you still need to modify data members inside a const member function -- without altering the observable state of the object. Such members are usually internal flags and other private bookkeeping variables that are not exposed to external clients. Let's look a concrete example. Class std::string represents its string as a char* member that points to an array of characters. Yet unlike traditional C-strings, the std::string char array doesn't need to append a '\0' terminator at its end because the length of the string is available by calling length() or size(). There is one exception to this rule: when you call string::c_str(). c_str() returns a const char * that points to a '\0' terminated char array. The most efficient way to satisfy this requirement is to have c_str() append the '\0' character. However, c_str() is a const member function. It cannot modify any data members of its string object -- unless they are declared mutable.
By declaring the string's char* member as mutable, the implementer of std::string can defer the appending of the '\0' character to c_str() member function. This way, not only does the implementation of class std::string become more efficient since it appends '\0' only when it must, but the string implementer also hides implementation details (e.g., at what stage exactly is the '\0' appended) from the clients.
Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.