|
||||
Section 18:
|
[18.16] Does "Fred const* p" mean that *p can't change?
No! (This is related to the FAQ about aliasing of int pointers.) "Fred const* p" means that the Fred can't be changed via pointer p, but there might be other ways to get at the object without going through a const (such as an aliased non-const pointer such as a Fred*). For example, if you have two pointers "Fred const* p" and "Fred* q" that point to the same Fred object (aliasing), pointer q can be used to change the Fred object but pointer p cannot. class Fred { public: void inspect() const; // A const member function void mutate(); // A non-const member function }; int main() { Fred f; Fred const* p = &f; Fred* q = &f; p->inspect(); // OK: No change to *p p->mutate(); // Error: Can't change *p via p q->inspect(); // OK: q is allowed to inspect the object q->mutate(); // OK: q is allowed to mutate the object f.inspect(); // OK: f is allowed to inspect the object f.mutate(); // OK: f is allowed to mutate the object ... } |