首页 > 解决方案 > 作为通用指针类型传递的 SmartPointers 是否需要在传递给另一个函数之前被释放?

问题描述

我认为智能指针在作为分配值的通用指针类型传递时需要专门删除,否则会发生内存或资源泄漏?

我将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);

?

标签: c++comatl

解决方案


它最终取决于开始指针和函数的编写方式,但一般来说,使用 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);

CComPtr::Release()请注意,即使包含的指针为空,知道可以安全地调用(在调试和发布模式下)也很好,所以这可以正常工作,例如:

CComPtr<ISomeComObj> mycomobj;
mycomobj.Release();

PS:我的建议是始终使用调试模式进行开发。


推荐阅读