gpt4 book ai didi

c++ - 为什么在使用 CComSafeArray 时会泄漏内存?

转载 作者:行者123 更新时间:2023-11-28 00:13:51 24 4
gpt4 key购买 nike

我有一个内存泄漏问题,我已将其缩小到以下代码。怎么回事?

CComSafeArray<BSTR> sa(5);
sa[0] = SysAllocString("constant");

CComSafeArray::~CComSafeArray调用 SafeArrayDestroy(通过 CComSafeArray::Destroy(),见下文),这 should then call SysFreeString在所有成员上。因此,这里不应该有泄漏。怎么回事?

HRESULT Destroy()
{
HRESULT hRes = S_OK;
if (m_psa != NULL)
{
hRes = Unlock();
if (SUCCEEDED(hRes))
{
hRes = SafeArrayDestroy(m_psa);
if (SUCCEEDED(hRes))
m_psa = NULL;
}
}
return hRes;
}

最佳答案

简答:

而不是在 CComSafeArray<BSTR> 中保存指针的拷贝, CComSafeArray<BSTR>::operator[]CComSafeArray<BSTR>::GetAt(T)返回 CComBSTR获取 BSTR 拷贝的对象.这导致 BSTR泄漏。

长答案:

几个小时无果而终后,在尝试编译一个更简单的版本以试图缩小漏洞时出现编译错误,暴露了它:

CComSafeArray<BSTR> sa(5);
sa[0] = nullptr;

这不会编译,因为在幕后CComSafeArray<BSTR>::operator[]返回 CComBSTR对象,和 nullptr可以同时匹配 CComBSTR::operator=(LPCSTR)CComBSTR::operator=(LPCOLESTR) .砰,编译错误。

一旦我发现CComBSTR被卷入幕后,就落到了实处。 CComBSTR::operator= takes a copy of the BSTR instead of saving the pointer (我如何阅读代码,给定正常行为)或取得所有权,导致未释放的临时文件泄漏 BSTR .

typename _ATL_AutomationType<T>::_typewrapper& GetAt(_In_ LONG lIndex) { ... }

...

// specialization for BSTR so GetT doesn't return &BSTR
template <>
struct _ATL_AutomationType<BSTR>
{
typedef CComBSTR _typewrapper ;
enum { type = VT_BSTR };
static void* GetT(_In_ const BSTR& t) throw()
{
return t;
}
};

关于c++ - 为什么在使用 CComSafeArray<BSTR> 时会泄漏内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31584738/

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