Search code examples
c++constantslanguage-lawyermutable

Does any enforcement mechanism exist for mutable meaning logical const?


The C++ keyword mutable lets us have non-const members in const objects. This raises the question, 'what? why?!', which has already been addressed on SO.

Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

The chosen answer is that the correct usage for mutable is to signify logical const as opposed to bitwise const. Several other questions and answers on SO raise the same point. I like these answers conceptually, but do they mean anything?

There's no mechanism in C++ to enforce logical const while allowing bitwise mutability that I know of. To take the idea at face value, using mutable would require compilers to deduce whether any possible write to a mutable member could ever cause the equality operator to evaluate false, which is just silly.

Herb Sutter's blog does confirm that logical const is at least the intent of mutable.

http://herbsutter.com/2013/05/24/gotw-6a-const-correctness-part-1-3/

" Similarly, writing mutable on a member variable means what it has always meant: The variable is “writable but logically const.” "

Is this any more than an intention? The standard itself is quite terse about mutable and I could not find a definition for "logically const".

Is there ever a case where a write to a mutable member of a const object that violates "logically const" is anything more than an aesthetically displeasing design?


Solution

  • "Logically const" can't be determined by mere equality. It may also include ordering and any hash function (including free functions in other Translation Units). There is no reasonable way for a compiler to determine exactly what contributes to logical const-ness, and therefore it can't determine whether any mutable member would influence such const-ness.