[LC++]How to use const member functions correctly?
Davide Bolcioni
9odb6x3rfr001 at sneakemail.com
Sat Sep 22 05:21:03 UTC 2001
Mark Phillips mark at austrics.com.au [mltuxcpp/linux-cpp list] wrote:
> My understanding of const member functions, is that by declaring
> it constant, you are giving a guarentee that it will not change
> the internals of the object.
Well, sort of. By declaring a member function const:
- you allow it to be called on const objects (or references/pointers
to such), while non-const member functions would be rejected by the
compiler;
- the hidden "this" pointer is a T const * const, not a T * const,
so the compiler will likewise reject calls to non-const members
of the this instance, assignments to members and conversions
which would break const (unless you use const_cast).
> But I have a problem. What if I have a member function which has
> a parameter passed by reference (non-constant). Passing by
> reference allows the function to modify an external variable.
> Normally this external variable will be unrelated to the internals
> of the object, so for most of the time, this function may be thought
> of as const. But what if somewhere, this function is used to modify
> an internal variable of the object --- by passing it in as the
> reference parameter --- then all of a sudden the function is non-const!
No, it is not. Read the above: inside a const member function, the
compiler only rejects non-const member functions called through "this",
it has no knowledge of aliasing. As suggested by C. Wood. if you have:
class C {
public:
int n;
void f(C& arg) const { arg.n = 3; }
...
}
and then
C c1;
C c2;
c1.n = 1;
c2.n = 2;
c1.f(c2); // Sets c2.n to 3.
c1.f(c1); // Sets c1.n to 3 ... oops, const changed.
> What should be done in this situation? Should I declare it const, and
> rely on the programmer to take care not to pass in the wrong parameter?
It depends on what you want to achieve. Personally, I make everything
const taking const arguments unless I have good reason not to; functions
modifying arguments are something I try to avoid as I have been bitten
on too many occasions.
Davide Bolcioni
--
Linux - the choice of a GNU generation.
More information about the tuxCPProgramming
mailing list