问题在最后两行代码中给出。
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?
谢谢
答案 0 :(得分:8)
SmartPtr<TestClass> sPtr(new TestClass);
TestClass* ptrA = sPtr->Detach();
实际上无效,因为TestClass
没有成员函数Detach
。 operator->
类的SmartPtr
被声明为T* operator->() const
,因此(应该)返回智能指针的pointee
。
TestClass* ptrB = sPtr.Detach();
是有效版本,因为sPtr
本身只是一个普通的本地堆栈变量,而不是指针。
答案 1 :(得分:0)
它们都是有效的语法,但调用不同的函数!
p.detach()将调用p对象的分离功能 p-&gt; detach()将调用对象p的分离函数,指向T
类型相当不同!