【发布时间】:2017-09-10 17:33:02
【问题描述】:
我正在使用CComPtr 类型的对象。但是我遇到了一些内存泄漏问题。特别是,我有以下代码:
CComPtr<ID2D1Bitmap> bitmap = create_bitmap(bitmapSize);
auto n = count_ref((ID2D1Bitmap*)bitmap);
地点:
template<class Interface>
ULONG count_ref(Interface* pInterface) noexcept
{
if (pInterface)
{
pInterface->AddRef();
return pInterface->Release();
}
return 0;
}
还有:
ID2D1Bitmap* create_bitmap(const D2D1_SIZE_U& size)
{
ID2D1Bitmap* bitmap;
CreateBitmap(&bitmap);
return bitmap;
}
我希望 n 的值等于 1,但它实际上等于 2。为什么我的 CComPtr 的引用计数不是 1?
我是否正确使用了我的CComPtr 对象?
当进程终止时,我得到以下内存泄漏:
An interface [072B1F50] was created but not released. Use 'dps 072B1F20' to view its allocation stack.
Object type: ID2D1Bitmap
Device-dependent size: 1000 x 600
Device-independent size: 1000.00 x 600.00
Format: DXGI_FORMAT_B8G8R8A8_UNORM
Alpha mode: D2D1_ALPHA_MODE_PREMULTIPLIED
Outstanding reference count: 1
D2D DEBUG ERROR - Memory leaks detected.
【问题讨论】:
-
使用 CComPtr::Attach() 获取接口指针的所有权。
标签: c++ memory-leaks com atl direct2d