【发布时间】:2019-05-03 02:50:42
【问题描述】:
我使用crtdbg检测泄漏位置,调用new时出现内存泄漏
CComPtr<IDBColumnInfo> m_spColumnInfo
CComPtr<CDBColumnInfo> spResult = new CDBColumnInfo(); //Memory leak here
//another logic come here to set data to spResult
//another logic come here to set data to spResult
//another logic come here to set data to spResult
m_spColumnInfo = static_cast<IDBColumnInfo*>(spResult.Detach());
spResult.Release();
spResult 是否需要执行任何步骤?
【问题讨论】:
-
为什么需要
spResult.Detach()?为什么不这样做:m_spColumnInfo = static_cast<CDBColumnInfo*>(spResult)?我有一段时间没有使用CComPtr,但是documentation 表示operator=会增加引用计数,所以通过使用Detach,我认为你最终会得到一个额外的AddRef而没有当您尝试转移所有权时,对应的Release。 -
没有更多细节了。尝试用我建议的行替换
spResult.Detach()行。 -
@jamesdlin 我在这个函数中遇到异常pastebin.com/LkWT2bhU
-
查看您的实际代码后:您根本不需要
delete spResult。另外,我会将spResult声明为CComPtr<IDBColumnInfo>,然后完全摆脱static_cast。 -
@jamesdlin 我改成
CComPtr<IDBColumnInfo> spResult = new CDBColumnInfo();,但是CDBColumnInfo的某些功能无法被spResult访问。例如HRESULT CDBColumnInfo::GetField (LPCOLESTR fieldName )
标签: c++ memory-leaks visual-leak-detector