[LC++]How to use const member functions correctly?
Davide Bolcioni
9odb6x3rfr001 at sneakemail.com
Sun Sep 23 06:58:04 UTC 2001
Carlo Wood carlo at alinoe.com [mltuxcpp/linux-cpp list] wrote:
>> c1.f(c1); // Sets c1.n to 3 ... oops, const changed.
> No oops imho, 'c1' changed - which is ok because 'c1' was NOT constant.
> If you'd try:
>
> C const c1;
> ...
> c1.f(c1);
>
> then the compiler would complain. So the code is perfectly safe.
Yes, I agree; the point of "oops" is that the "const" member
function .f() changed c1, the instance is it applied to - so
you find c1 changed in a place where you would not expect to
in real code, where the aliasing would not be so obvious.
Your suggestion
assert(&arg != this);
seems entirely appropriate for const member functions taking a
modifiable reference or pointer argument to their type (or an
ancestor, I guess) just to guard against this surprise.
With multiple inheritance or when operator& is redefined things
may need more care, but the reasoning I agree with entirely.
Davide Bolcioni
--
There is no place like /home.
More information about the tuxCPProgramming
mailing list