how does the compiler implement it?
Before asking how the compiler handles mutable
, you should ask how the compiler handles const
.
As the name implies, mutable
is just another qualifier (or rather a storage class specifier) that interacts with how const
is handled. It simply means that a mutable
member variable can be modified, even if the containing object is declared const
. It can also be modified through a const
reference (or pointer) to the containing object. It does not directly relate to member functions.
Note that a mutable
member variable cannot be modifier through a direct const
reference (or pointer).
When looking at a mutating operation on a symbol, the compiler simply checks whether the symbol can be mutated in this context according to the rules above.
Example:
struct S {
mutable int i;
};
int main() {
S const object{0};
object.i = 1; // ok because object.i is qualified `mutable`, even if object is `const`
S const& ref = object;
ref.i = 2; // ok because ref refers to an object that has a `mutable` member `i`
int const& direct_ref = object.i;
direct_ref = 3; // error because direct_ref directly refers to a `const` symbol
}