为什么此代码会泄漏内存?(出论点和指针)

Why does this code leak memory? (Out arguments and pointers)

本文关键字:指针 代码 泄漏 内存 为什么      更新时间:2023-10-16

我是C++新手。 我编写此方法是为了轮询加速度计。 它被反复调用,并泄漏内存。

AccelSample SensorObj::GetReport() {
    ISensorDataReport* pReport;
    HRESULT hr = pSensor->GetData(&pReport);
    // theoretically, i would fill this struct with the values from pReport, but this is just here for testing.
    AccelSample sample;
    sample.x = 0;
    sample.y = 0;
    sample.z = 0;
    sample.timestamp = 0;
    return sample;
}

HRESULT hr = pSensor->GetData(&pReport);

似乎是泄漏的来源。 如果我把它注释掉,就没有泄漏。 GetData 的定义是

virtual HRESULT STDMETHODCALLTYPE GetData(__RPC__deref_out_opt ISensorDataReport **ppDataReport) = 0;

此 API 的文档显示 GetData 的调用方式相同。https://msdn.microsoft.com/en-us/library/windows/desktop/dd318962%28v=vs.85%29.aspx

如果我理解正确,GetData 会取出一个指向指针的指针的 out 参数。 通过将 &pReport 传递给它,我传递了指针 pReport 的"地址"。 是吗? 这不应该没问题吗?

编辑:我应该提到我尝试过"删除pReport"。 我收到一个错误,说"调试断言失败。_BLOCK_TYPE_IS_VALID(pHead->nBlockUse".

此代码违反了 COM 的引用计数机制,并且当您只有一个对对象的引用时工作正常:

delete pReport  

通常,您应该调用发布方法或使用 CComPtr 智能指针:

CComPtr<ISensorDataReport> pReport;
HRESULT hr = pSensor->GetData(&pReport);