C++ -- Why should we use operator -> to access member functions of a SmartPtr?

Posted by q0987 on Stack Overflow See other posts from Stack Overflow or by q0987
Published on 2011-03-06T00:05:15Z Indexed on 2011/03/06 0:11 UTC
Read the original article Hit count: 184

Filed under:

Hello all,

The question is given in the last two lines of code.

template<class T>                    // template class for smart
class SmartPtr {                     // pointers-to-T objects
public:
  SmartPtr(T* realPtr = 0);

  T* operator->() const;
  T& operator*() const;

  T* Detach( void )
  {
    T* pData = pointee;
    pointee = NULL;
    return pData;
  }  

private:
  T *pointee;
  ...
};

class TestClass {}

SmartPtr<TestClass> sPtr(new TestClass);

TestClass* ptrA = sPtr->Detach(); // why I always see people use this method to access member functions of a Smart pointer.
We can use sPtr-> b/c we have defined operator->() in SmartPtr.    

TestClass* ptrB = sPtr.Detach();  
// Question: Is this a valid C++ way? If not, why?

Thank you

© Stack Overflow or respective owner

Related posts about c++