| the updateCachedWidth example probably gives the wrong idea to a lot of folks. You would be just as well off making computeWidth const/pure/readonly/whatever The compiler can even detect if it modifies anything and mark it for you.
In fact, better compilers will compute mod/ref information and know that m_cachedWidth is not touched over that call. However, LLVM's (which is what at least Apple is using) basic stateless alias analysis is not good enough to do this in this kind of case (there are some exceptions where it might be able to, none apply here) This is actually a great example of how improving pointer and alias analysis in a compiler buys you gains, and not an example of "how you should modify your code", since you generally should not modify your code to work around temporary single-compiler deficiencies without very good reason. Especially considering how quickly compiler releases are pushed by Apple/et al. |
Even if it is not, I still think this is an example of "how you should modify your code". Reason? Doing
keeps your state consistent in case bar() throws. I would even use it if bar() is known not to throw, because you can't know what the future will bring, and because what you 'know' sometimes isn't true. Defensive programming, if easy as in this case, is a net benefit.