用于管理 COM 接口指针的智能指针类。
语法
template<class T>
class CComPtr
参数
T
一个 COM 接口,指定要存储的指针的类型。
成员
公共构造函数
| 名称 | 描述 |
|---|---|
CComPtr::CComPtr |
构造函数。 |
公共运算符
| “属性” | 描述 |
|---|---|
CComPtr::operator = |
将指针分配给成员指针。 |
注解
ATL 使用 CComPtr 和 CComQIPtr 管理 COM 接口指针。 两者都派生自 CComPtrBase,且两者都执行自动引用计数。
CComPtr 和 CComQIPtr 类可以通过执行自动引用计数来帮助消除内存泄漏。 以下函数执行相同的逻辑操作。 但是,第二个版本可能不太容易出错,因为它使用 CComPtr 类:
// Error-checking routine that performs manual lifetime management
// of a COM IErrorInfo object
HRESULT CheckComError_Manual()
{
HRESULT hr;
CComBSTR bstrDescription;
CComBSTR bstrSource;
CComBSTR bstrHelpFile;
IErrorInfo* pErrInfo = NULL; // naked COM interface pointer
hr = ::GetErrorInfo(0, &pErrInfo);
if(hr != S_OK)
return hr;
hr = pErrInfo->GetDescription(&bstrDescription);
if(FAILED(hr))
{
pErrInfo->Release(); // must release interface pointer before returning
return hr;
}
hr = pErrInfo->GetSource(&bstrSource);
if(FAILED(hr))
{
pErrInfo->Release(); // must release interface pointer before returning
return hr;
}
hr = pErrInfo->GetHelpFile(&bstrHelpFile);
if(FAILED(hr))
{
pErrInfo->Release(); // must release interface pointer before returning
return hr;
}
pErrInfo->Release(); // must release interface pointer before returning
return S_OK;
}
// Error-checking routine that performs automatic lifetime management
// of a COM IErrorInfo object through a CComPtr smart pointer object
HRESULT CheckComError_SmartPtr()
{
HRESULT hr;
CComBSTR bstrDescription;
CComBSTR bstrSource;
CComBSTR bstrHelpFile;
CComPtr<IErrorInfo> pErrInfo;
hr = ::GetErrorInfo(0, &pErrInfo);
if(hr != S_OK)
return hr;
hr = pErrInfo->GetDescription(&bstrDescription);
if(FAILED(hr))
return hr;
hr = pErrInfo->GetSource(&bstrSource);
if(FAILED(hr))
return hr;
hr = pErrInfo->GetHelpFile(&bstrHelpFile);
if(FAILED(hr))
return hr;
return S_OK;
} // CComPtr will auto-release underlying IErrorInfo interface pointer as needed
在调试版本中,链接 atlsd.lib 进行代码跟踪。
继承层次结构
CComPtr
要求
标头:atlbase.h
CComPtr::CComPtr
构造函数。
CComPtr() throw ();
CComPtr(T* lp) throw ();
CComPtr (const CComPtr<T>& lp) throw ();
参数
lp
用于初始化接口指针。
T
COM 接口。
备注
在 lp 上采用参数调用 AddRef 的构造函数(如果不是 null 指针)。 在 CComPtr 对象销毁时,或者如果向 CComPtr 对象分配了一个新对象,非 null 拥有的对象会获取 Release 调用。
CComPtr::operator =
赋值运算符。
T* operator= (T* lp) throw ();
T* operator= (const CComPtr<T>& lp) throw ();
返回值
返回指向更新后的 CComPtr 对象的指针
备注
此操作对新对象执行 AddRefs 并释放现有对象(如果存在)。