Topic: mutable keyword, why do we need it?
Author: robina@wv.mentorg.com (Robin Albrecht)
Date: Thu, 11 Nov 1993 17:40:45 GMT Raw View
In article <CGAxK5.3vz@cbnewse.cb.att.com>, grumpy@cbnewse.cb.att.com (Paul J Lucas) writes:
|> From article <1993Nov10.003628.26033@Synopsys.Com>, by jbuck@synopsys.com (Joe Buck):
|> > tsai@vsc_ecad.vitsemi.com (Jodi Tsai) writes:
|> >>Why was the mutable extension added to the language? How does mutable differ
|> >>from just recasting the "this" pointer to a non-const type?
|> >
|> > Casting the "this" pointer permits any member to be modified. "mutable",
|> > together with a rigorous standard that says "one does not cast away
|> > const", defines exactly which members may be modified by const methods
|> > and does not throw all protection away.
|>
|> This solution has a bias toward the data-member; what if I want
|> a data member to be "mutable" only in particular
|> member-functions?
I'm don't know whether anything should be "mutable", but if mutability is going
to be added, I think that const-ness is better preserved by allowing member
functions to be "mutable", allowing them to modify any data member without
requiring a cast. Thus, in the common example of a class that does some type
of caching, a small number of methods that deal with the caching can be defined
and declared mutable, and no other methods can accidentally violate const.
Clearly, further protection would be added by specifying that only certain
methods can modify only certain data members. (Many people think that 'friend'
access would be enhanced by allowing this type of granularity, too.)
|> I saw nothing wrong with casting away const; it meant you had to
|> make a conscious effort to do it which implies you had to think
|> about it and what you're doing. Thinking is good.
Agreed. However, many compilers issue warnings when const is cast away. We
have found that if too many warnings are generated, all warnings end up being
ignored, which risks introducing errors (we're using Cfront 2.1, in which many
warnings indicate actual errors). By providing "mutable", one can avoid the
generation of warnings where the warnings are not useful -- with of course the
danger that warnings will also not be generated where const-ness is being
violated uninitentionally.
|> --
|> - Paul J. Lucas
|> AT&T Bell Laboratories
|> Naperville, IL
--
Robin Albrecht
Mentor Graphics, IC Division
Email: robin_albrecht@mentorg.com