简体   繁体   中英

C++ Overloading -> operator, how does it work?

I was trying to implement a smart pointer class similar to the standard library auto_ptr and accordingly I had to overload the -> operator for the same. Here is my code

template <typename T>
class SmartPtr
{

   T * operator -> ()
  {
    return _pAct;
  }

 private:
 T * _pAct;
};

Rest of the implementation is not shown so as to avoid diversion from my query.

Now I create a SmartPtr of class A and call a method Show() present in A on it :

SmartPtr smPtr(new A);
smPtr->Show();

Here is my query(don't know if its valid also)

Since SmartPtr::operator->() return A*, the call to show should translate to (A*)Show. Why it translates to (A*)->Show() ?

or in other words how does smPtr->Show() mean call Show() on whatever smPtr->() operator returns ?

Because operator -> applies sequentially until it can't be applied any more.

13.5.6 Class member access [over.ref]

1) operator-> shall be a non-static member function taking no parameters. It implements class member access using -> postfix-expression -> id-expression An expression x->m is 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). (emphasis mine)

Which means, in your case, it translates to:

smPtr.operator->()->Show();
          |           |
      returns A*   call Show on the A*

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM