No, it's not correct. The code calls SelectObject()
to select the bitmap into the device context, then calls DeleteObject()
in an attempt to delete the bitmap while it's still selected in the device context. In this case, DeleteObject()
will fail, so the bitmap is leaked.
http://msdn.microsoft.com/en-us/library/dd183539(v=vs.85).aspx
"Do not delete a drawing object (pen or brush) while it is still selected into a device context."
EDIT:
Well, that's interesting. I tried calling DeleteObject()
while a bitmap is selected in the device context, and it returns 1 for me too. Interestingly, the bitmap is not actually deleted at this point; calling GetObject()
on the "deleted" bitmap succeeds! However, as soon as the deleted bitmap is selected out of the device context, then it is actually deleted; calling GetObject()
fails at that point. I also verified by watching the GDI handle count in Task Manager. So, apparently DeleteObject()
will defer the deletion if the bitmap is currently selected into a device context, though I don't believe that's documented anywhere.
HDC hdc = CreateCompatibleDC(NULL);
if (hdc != NULL) {
HBITMAP hBitmap = LoadBitmap(hInst, MAKEINTRESOURCE(IDB_SAMPLE));
BITMAP bm = { 0 };
int numBytes;
// this succeeds as expected
numBytes = GetObject(hBitmap, sizeof(BITMAP), &bm);
HBITMAP hOldBitmap = SelectBitmap(hdc, hBitmap);
DeleteObject(hBitmap);
// this succeeds -- NOT expected!
numBytes = GetObject(hBitmap, sizeof(BITMAP), &bm);
SelectBitmap(hdc, hOldBitmap);
// this fails as expected
numBytes = GetObject(hBitmap, sizeof(BITMAP), &bm);
DeleteDC(hdc);
}
The bottom line is that the code you posted appears to work, but is dependent on undocumented behavior. My preference would be to play it safe and eliminate that dependency.