我有以下代码块
/////////////////////////////////////
CComVariant newVal;
//pass the CComVariant and get the strings array!!!
GetStrList(newVal);
USES_CONVERSION;
if (((newVal.vt & VT_ARRAY) == VT_ARRAY) && ((newVal.vt & VT_BSTR) == VT_BSTR))
{
SAFEARRAY* paArray = newVal.parray;
BSTR * str = NULL;
SafeArrayAccessData(paArray, (void**)&str);
SafeArrayUnaccessData(paArray);
long lLBound = 0;
long lUBound = 0;
long nCount = 0;
if (FAILED(SafeArrayGetLBound(paArray, 1, &lLBound)) ||
FAILED(SafeArrayGetUBound(paArray, 1, &lUBound)))
{
ASSERT(false);
return FALSE;
}
nCount = ( lUBound - lLBound + 1 );
for (int i = 0 ; i < nCount ; i++)
{
m_cstrList.AddString(W2T(str[i]));
}
//SafeArrayDestroy(paArray); ---> is it required here???
}
/////////////////////////////////////
方法重新安全数组
HRESULT GetStrList(VARIANT *pVal)
{
USES_CONVERSION;
if (!pVal)
return E_FAIL;
SAFEARRAYBOUND bound[1]; //single dimension array
bound[0].lLbound = 0;
bound[0].cElements = 10;
SAFEARRAY * A = SafeArrayCreate(VT_BSTR, 1, bound);
BSTR * str = NULL;
SafeArrayAccessData(A, (void**)&str);
//user wants the NT view OPC drivers list.
for (int i=0;i<10;i++)
{
str[i] = SysAllocString(T2W(mystrings[i]));
}
VariantInit(pVal);
pVal->vt = VT_ARRAY | VT_BSTR;
pVal->parray = A;
SafeArrayUnaccessData(A);
A = NULL;
return S_OK;
}
我的疑问是,上面的第一个代码块有任何内存泄漏?
CComVariant
本身是否处理清洁的所有事情?
或者我也手动执行SafeArrayDestroy(paArray);
提前致谢!
答案 0 :(得分:3)
CComVariant析构函数调用VariantClear(),它释放变量包含的任何内容,包括数组。
一个警告:调用VariantClear()时不应锁定数组。这意味着如果在SafeArrayAccessData()之后但在SafeArrayUnaccessData()之前抛出异常,则不会调用后者,并且VariantClear()不会释放资源。
因此,您最好编写一个括号类,用于配对SafeArrayAccessData()和SafeArrayUnaccessData()调用。