smart pointers like shared_ptr can be used like ordinary pointers with * and -> operator.
The books say that -> operator returns the pointer that shared_ptr stores. So you can use it to access the object this pointer points to. But I am confused here. Look at the code below.
class A
{
public:
    A(int v = 20){val = v;}
    int val;
}
A* p1 = new A;
std::cout<<p1->val;  //This is common sense
boost::shared_ptr<A> p2(new A);
std::cout<<p2->val;  //This is right
//My question is that p2-> returns the pointers of the object, then maybe another 
//-> should be used?
//like (p2->)->val? 
                It's magic. Well, more like a special case. The standard says that
13.5.6 Class member access [over.ref]
1
operator->shall be a non-static member function taking no parameters. It implements the class member access syntax that uses->.postfix-expression -> templateopt id-expression
postfix-expression -> pseudo-destructor-nameAn expression
x->mis interpreted as(x.operator->())->mfor a class objectxof typeTifT::operator->()exists and if the operator is selected as the best match function by the overload resolution mechanism (13.3).
That is, operator-> is called again on the result of the overloaded operator. And if that one is overloaded too, it goes on recursively until a raw pointer is the result and the built-in operator-> is called.
That doesn't mean the result can't be any arbitrary type - it can be, but then you can only call it with the function call syntax:
struct X {
    int operator->() { return 42; }
};
int main()
{
    X x;
    x.operator->(); // this is OK
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With