c++ - 作为通用指针类型传递的 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);
?
解决方案
它最终取决于开始指针和函数的编写方式,但一般来说,使用 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:我的建议是始终使用调试模式进行开发。
推荐阅读
- javascript - parseFloat 在 Javascript 中不返回准确的值
- java - 使用 Java Stream API 进行分层过滤
- delphi - 如何安装 Delphi 10.4 Sydney 命令行编译器(在 Windows Server 2016 上)?
- multithreading - Flask同时为不同的网站访问者分配不同的ID,并将他们的输入信息写入json文件
- python - SymPy 中的非笛卡尔坐标积分
- java - 可选和 Java Spring 测试
- jquery - 当某些数字以k结尾时如何使用Jquery进行排序?
- bash - 比 shell 脚本更有效的 Bash 变量
- python - 合并或映射具有唯一列名或特定条件的 DataFrame
- perl - 将字符串拆分为哈希散列(perl)