No, that is not right. The code calls SelectObject() to select a bitmap in the device context, then calls DeleteObject() in an attempt to delete the bitmap while it is still selected in the device context. In this case, DeleteObject() will fail, so the bitmap will leak.
http://msdn.microsoft.com/en-us/library/dd183539(v=vs.85).aspx
"Do not delete the drawing object (pen or brush) while it is still selected in the device context."
EDIT:
Well, that is interesting. I tried calling DeleteObject() while the bitmap was selected in the device context and it returns 1 for me too. Interestingly, the bitmap is not actually deleted at the moment; calling GetObject() on a "remote" raster file succeeds! However, once the deleted bitmap is selected outside the device context, it is actually deleted; the call to GetObject() fails at this point. I also checked by looking at the counter of the GDI descriptors in the task manager. Thus, it is obvious that DeleteObject() will DeleteObject() deletion if the bitmap is currently selected in the device context, although I do not believe that this is documented somewhere.
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 created works, but depends on undocumented behavior. My preference would be to ensure its safety and eliminate this addiction.
source share