作为通用指针类型传递的 SmartPointer 是否需要在传递给另一个函数之前被释放?

Do SmartPointers passed as a generic pointer type need to be freed before passing to another function?

我认为智能指针在作为通用指针类型传递并被赋值时需要特别删除,否则会发生内存或资源泄漏?

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

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

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

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