我是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)”。
发布于 2015-04-11 03:39:15
这段代码违反了COM的ref计数机制,并且在只有一个对象引用时工作正常:
delete pReport 通常,您应该调用Release方法或使用CComPtr智能指针:
CComPtr<ISensorDataReport> pReport;
HRESULT hr = pSensor->GetData(&pReport);https://stackoverflow.com/questions/29572854
复制相似问题