From my understanding , mutable
cancels the constness
of a variable
Class A {
void foo() const {
m_a = 5;
}
mutable int m_a;
};
>
The difference is semantic - i. e. same generated code, same run-time results (const
ness is a purely compile-time construct anyway), but the two constructs convey a slightly different meaning.
The idea is that you use mutable
for variables that are in the class, but don't constitute the state of the object. The classic example is the current position in a blob object. Navigating in the blob does not count as "modifying" the blob in a way that matters. By using mutable
, you're saying "this variable may change, but the object is still the same". You're stating that for this particular class, const
-ness does not mean "all variables are frozen".
const_cast
, on the other way, means that you're violating existing const correctness and hope to get away with it. Probably because you're working with a 3rd party API that does not respect const
(e. g. an old school C-based one).