Reputation: 35
I have a class in MFC derived from CBitmap, named BitmapTools.
In it, a function loads and attaches a Bitmap, as shown below.
bool BitmapTools::LoadAttachBitmap(LPCSTR bmpfile)
{
H_Bitmap = (HBITMAP)LoadImage(NULL, bmpfile, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION);
return Attach (H_Bitmap);
}
When the class goes out of scope and is destroyed, do I need to detach the bitmap and call DeleteObject, to free memory?
I added the following in the destructor, but from what I have read, I am not sure if this is necessary.
BitmapTools::~BitmapTools()
{
this->Detach();
DeleteObject();
}
Thanks,
Hugh
Upvotes: 2
Views: 1603
Reputation: 50036
No, you dont have to - CBitmap derives from CGdiObject which destructor looks like below:
_AFXWIN_INLINE CGdiObject::~CGdiObject()
{
AFX_BEGIN_DESTRUCTOR
DeleteObject();
AFX_END_DESTRUCTOR
}
DeleteObject();
is implemented as follows:
BOOL CGdiObject::DeleteObject()
{
if (m_hObject == NULL)
return FALSE;
return ::DeleteObject(Detach());
}
so it both detaches and deletes any attached objects.
All the sources for MFC are available in you VS directory, above sources are from older version VS2005, but should be similar to newer ones.
You should be able to use debugger to step into destructor of your class and upper classes - just press F11 all the time.
Upvotes: 2
Reputation: 188
You dont have to delete it and you wont have any memory or resource leak if you dont but MS says that you should
MSDN LoadImage function (Remarks section)
So you have done great
Upvotes: 0