一个智能指针实际上就是重载了操作符"->"的类。智能指针类包含指向另外一个对象的指针。当用户调用智能指针上的"->"操作符时,智能指针将把此调用委托或转发给它所包含的指针所指的对象。智能接口指针是一个智能指针,它所包含的指针指向一个接口。
COM接口智能指针类CComPtr:
template <class T>
class CComPtr
{
public:
typedef T _PtrClass;
CComPtr()
{
p=NULL;
}
CComPtr(T* lp)
{
if ((p = lp) != NULL)
p->AddRef();
}
CComPtr(const CComPtr<T>& lp)
{
if ((p = lp.p) != NULL)
p->AddRef();
}
~CComPtr()
{
if (p)
p->Release();
}
void Release()
{
IUnknown* pTemp = p;
if (pTemp)
{
p = NULL;
pTemp->Release();
}
}
operator T*() const
{
return (T*)p;
}
T& operator*() const
{
ATLASSERT(p!=NULL);
return *p;
}
//The assert on operator& usually indicates a bug. If this is really
//what is needed, however, take the address of the p member explicitly.
T** operator&()
{
ATLASSERT(p==NULL);
return &p;
}
_NoAddRefReleaseOnCComPtr<T>* operator->() const
{
ATLASSERT(p!=NULL);
return (_NoAddRefReleaseOnCComPtr<T>*)p;
}
T* operator=(T* lp)
{
return (T*)AtlComPtrAssign((IUnknown**)&p, lp);
}
T* operator=(const CComPtr<T>& lp)
{
return (T*)AtlComPtrAssign((IUnknown**)&p, lp.p);
}
bool operator!() const
{
return (p == NULL);
}
bool operator<(T* pT) const
{
return p < pT;
}
bool operator==(T* pT) const
{
return p == pT;
}
// Compare two objects for equivalence
bool IsEqualObject(IUnknown* pOther)
{
if (p == NULL && pOther == NULL)
return true; // They are both NULL objects
if (p == NULL || pOther == NULL)
return false; // One is NULL the other is not
CComPtr<IUnknown> punk1;
CComPtr<IUnknown> punk2;
p->QueryInterface(IID_IUnknown, (void**)&punk1);
pOther->QueryInterface(IID_IUnknown, (void**)&punk2);
return punk1 == punk2;
}
void Attach(T* p2)
{
if (p)
p->Release();
p = p2;
}
T* Detach()
{
T* pt = p;
p = NULL;
return pt;
}
HRESULT CopyTo(T** ppT)
{
ATLASSERT(ppT != NULL);
if (ppT == NULL)
return E_POINTER;
*ppT = p;
if (p)
p->AddRef();
return S_OK;
}
}
在做语音软件开发的时候接触到智能指针的概念,例如要用到以下的代码:
CComPtr<ISpRecoContext> cpRecoCtxt;
CComPtr<ISpRecoGrammar> cpGrammar;
CComPtr<ISpVoice> cpVoice;