C++ -- Why should we use operator -> to access member functions of a SmartPtr?
- by q0987
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