Re: mutable vs const_cast, which is better to modify field from const function?
"Qi" <no@no.com>
It's not rare to lazy initialize member field in getter functions which
are const function.
Changing the state of an object from a const function is generally NOT FAIR.
We use mutable members to have elements that are not considered as part of
the state. Like memoize cache. That can be recreated from real state.
Your case is not clear where it belongs. If you have a special "empty"
state, the getter discovers, it can use it to answer the query, and there is
no need to alter anything.
If you do alter the state, it is better to be honest about it. And not do it
with either cast or mutable.
For really non-state members, prefer mutable, and make special
documentation/warning on that. In multithreaded world peope normally map
logical constness to physical one, and may be hit by race conditions.
Also, modifying an object that was originally created const is undefined
behavior.
Doing const_cast inside class may still be fair game in circumstances you
are sure you had a non-const instance, and only gained and excess const
somehow -- or you're forcing some overloads.