作为通用指针类型传递的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);

请注意,即使所包含的指针为null,也可以安全地(在调试和释放模式下)调用CComPtr::Release(),例如,

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

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...