I think it is a good idea to have const-overloaded arrow operator in counted pointer idiom though the Coplien's book does not say about it. This is required to "carry forward" the const-ness from the handle object to the body pointer held inside the handle. Counted body idiom is useful when you do not want to add corresponding (mirror) functions in handle class when you add functions in the body class. Handle class can actually be template. (CORBA _var classes?) The arrow operator takes care of "automatic" forwarding.
class String // this is handle
{
...
Stringrep *operator -> () const { return b_; }
private:
Stringrep *b_;
}
class Stringrep // this is body
{
void func (); // a non-const function.
}
main() {
const String s (new Stringrep);
s->func (); // invokes a non-const function of stringrep (body) when handle object is const.
}
In order to prevent this undetected mishap declare vonst-overloaded arrow operators.
class String
{
...
const Stringrep *operator -> () const { return b_; }
Stringrep *operator -> () { return b_; }
private:
Stringrep *b_;
}
Depending upon the const-ness of the handle object, it will invoke the right const-overloaded arrow operator and therefore, const-ness of body pointer comes along with it and therefore, compiler will prevent invocation of non-const member method of the body class using a const handle object. This is important because handle-body are logically the same entity for the client of the abstraction.
class String // this is handle
{
...
Stringrep *operator -> () const { return b_; }
private:
Stringrep *b_;
}
class Stringrep // this is body
{
void func (); // a non-const function.
}
main() {
const String s (new Stringrep);
s->func (); // invokes a non-const function of stringrep (body) when handle object is const.
}
In order to prevent this undetected mishap declare vonst-overloaded arrow operators.
class String
{
...
const Stringrep *operator -> () const { return b_; }
Stringrep *operator -> () { return b_; }
private:
Stringrep *b_;
}
Depending upon the const-ness of the handle object, it will invoke the right const-overloaded arrow operator and therefore, const-ness of body pointer comes along with it and therefore, compiler will prevent invocation of non-const member method of the body class using a const handle object. This is important because handle-body are logically the same entity for the client of the abstraction.
Comments