gpt4 book ai didi

c++ - 在传递给另一个函数之前,是否需要释放作为通用指针类型传递的 SmartPointers?

转载 作者:行者123 更新时间:2023-12-03 07:01:00 25 4
gpt4 key购买 nike

我认为当作为通用指针类型传递时需要专门删除智能指针,该类型被分配一个值或者会发生内存或资源泄漏吗?
我会用 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 指针和函数应按其编码方式编写:
在 Debug模式下:

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()即使包含的指针为空,也可以安全地调用(在调试和 Release模式下),因此这可以正常工作,例如:
CComPtr<ISomeComObj> mycomobj;
mycomobj.Release();
PS:我的建议是始终使用 Debug模式进行开发。

关于c++ - 在传递给另一个函数之前,是否需要释放作为通用指针类型传递的 SmartPointers?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63855894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com