I saw the following example in book of the C++ Programming Language
class Ptr {
X* operator->( );
};
voide f(Ptr p)
{
p->m=7;
X* q1 = p->;
X* q2 = p.operator->();
}
The book claims that
1)Objects of class Ptr can be used to access members of class X in a very similar manner to the way pointers are used.
2)The transformation of the object p into the pointer p.operator->() does not depend on the member m pointed to. That is the sense in which operator->( ) is a unary postfix operator.
For the first point, I do not understand why we need to this design, or in which scenarios should use this kind of design.
For the second point, I am confused about the message that the author want to deliver.
Thanks.
This design is extremely useful when we want to create a class that behaves like a pointer; this is the case of smart pointers (objects that have a pointer-like interface but that provide additional "services", e.g. automatic deallocation on destruction, ownership transfer, reference counting, …).
Notice that often this kind of object will also overload the
*(dereference) operator to mimic pointers more closely.The author wants to say that when you use the
->operator onPtr, it’s not relevant (as far asoperator->is concerned) what you put after it: in any case, theoperator->method will be called, that will return a pointer to the object that will be considered for the rest of the expression.To make this more clear: quoting directly from the standard:
In other words:
operator->()directly (second and third example in the OP code), you will get the pointer returned by theoperator->method, just like what happens with any method;->operator (e.g.x->m, as in the first example in the OP code), the overloadedoperator->will be called, and the returned pointer will be used as if the->mwas being used over it.