All I know is that f isn't aware of the internal working of mutate, it
just
knows the contract, which is that mutate receives a reference to const.
Therefore f can assume that *p cannot change and therefore can cache its
value throughout the function.
Yes, that is the contract and it is true that a function that takes a
reference to const and casts away const and modifies it is bad. But
the point I am making is that if the object when declared as non-
const, is passed to such a function, it is not undefined behavior. It
is only undefined behaviour if the object passed to this function was
a const object (const declaration for creating it). I am not saying
such functions are a good programming style, its bad bad bad since f()
can not really know if the constified object is actually a const or
not (may be with some effort but it won't make it a good function).
Here is a reference -
http://groups.google.co.in/group/comp.lang.c++.moderated/msg/955f2471ef8d7801
- Note that the call f(poly) is fine. It does not result in undefined
behaviour because poly is not a const object. But cpoly is and hence
f(cpoly) is undefined behaviour.
I guess, when in f(), as soon as a const_cast is applied and the
object is non-const, the compiler has to make sure that it writes the
change at the memory where the object resides and not the cached value.
There is no const_cast applied in f. mutate could be in a different
translation unit, or even in a dynamic library updated after the compile.