为什么这段代码会泄漏内存? (输出参数和指针)
Why does this code leak memory? (Out arguments and pointers)
我是 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 传递给它,我将 "address of" 指针 pReport 传递给它。那正确吗?这样应该没问题吧?
编辑:我应该提到我试过 "delete pReport"。我收到类似 "Debug assertion failed. _BLOCK_TYPE_IS_VALID(pHead->nBlockUse".
的错误消息
此代码违反了 COM 的引用计数机制,并且当您只有一个对象引用时可以正常工作:
delete pReport
一般情况下,应该调用Release方法或者使用CComPtr智能指针:
CComPtr<ISensorDataReport> pReport;
HRESULT hr = pSensor->GetData(&pReport);
我是 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 传递给它,我将 "address of" 指针 pReport 传递给它。那正确吗?这样应该没问题吧?
编辑:我应该提到我试过 "delete pReport"。我收到类似 "Debug assertion failed. _BLOCK_TYPE_IS_VALID(pHead->nBlockUse".
的错误消息此代码违反了 COM 的引用计数机制,并且当您只有一个对象引用时可以正常工作:
delete pReport
一般情况下,应该调用Release方法或者使用CComPtr智能指针:
CComPtr<ISensorDataReport> pReport;
HRESULT hr = pSensor->GetData(&pReport);