C ++ - 我们为什么要使用operator - >访问SmartPtr的成员函数?

时间:2011-03-06 00:05:16

标签: c++

问题在最后两行代码中给出。

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?

谢谢

2 个答案:

答案 0 :(得分:8)

SmartPtr<TestClass> sPtr(new TestClass);
TestClass* ptrA = sPtr->Detach();

实际上无效,因为TestClass没有成员函数Detachoperator->类的SmartPtr被声明为T* operator->() const,因此(应该)返回智能指针的pointee

TestClass* ptrB = sPtr.Detach();

是有效版本,因为sPtr本身只是一个普通的本地堆栈变量,而不是指针。

答案 1 :(得分:0)

它们都是有效的语法,但调用不同的函数!

p.detach()将调用p对象的分离功能 p-&gt; detach()将调用对象p的分离函数,指向T

类型

相当不同!