问题描述
我认为智能指针在作为通用指针类型传递时需要特别删除,因为该通用指针类型被分配了一个值,否则会发生内存或资源泄漏?
我将以CComPtr
为例。会泄漏吗?
CComPtr<ISomeComObj> mycomobj;
SomeOtherComObject1->FunctionToFindComObject(&mycomobj);
SomeOtherComObject2->FunctionToFindComObject(&mycomobj);
如果是这样,我认为解决方案是:
CComPtr<ISomeComObj> mycomobj;
SomeOtherComObject1->FunctionToFindComObject(&mycomobj);
mycomobj=NULL;
SomeOtherComObject2->FunctionToFindComObject(&mycomobj);
或CString示例:
void GetString(char **pstring)
{
*pstring=new char[123];
strncpy(*pstring,"Whatever",122);
}
// this leaks,correct?
CString s;
GetString(&s);
GetString(&s);
// this is okay,correct?
CString c;
GetString(&c);
c=NULL;
GetString(&c);
?
解决方法
这最终取决于起始指针和函数的编写方式,但总的来说,ATL指针和函数应按如下方式进行编码:
在调试模式下:
CComPtr<ISomeComObj> mycomobj;
SomeOtherComObject1->FunctionToFindComObject(&mycomobj);
SomeOtherComObject2->FunctionToFindComObject(&mycomobj); // will throw an ATL assert
从atlcomcli.h
中提取:
...
//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&() throw()
{
ATLASSERT(p==NULL);
return &p;
}
...
在发行版中,您将遇到问题。所以你应该做的是这样:
CComPtr<ISomeComObj> mycomobj;
SomeOtherComObject1->FunctionToFindComObject(&mycomobj);
mycomobj.Release();
SomeOtherComObject2->FunctionToFindComObject(&mycomobj);
请注意,即使所包含的指针为null,也可以安全地(在调试和释放模式下)调用CComPtr::Release()
,例如,
CComPtr<ISomeComObj> mycomobj;
mycomobj.Release();
PS:我的建议是始终使用调试模式进行开发。