Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the operator-> return value of smart pointers [duplicate]

Tags:

c++

pointers

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? 
like image 468
richard.g Avatar asked Dec 14 '13 12:12

richard.g


1 Answers

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-name

An expression x->mis interpreted as (x.operator->())->m for a class object x of type T if T::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
}
like image 172
jrok Avatar answered Oct 06 '22 20:10

jrok