Is there some kind of NULL Handle in Windows? If I create a bmp via CreateCompatibleBitmap() and delete it via DeleteObject() and want to use move semantics, I want to make sure that the bitmap is not destroyed. Hence I have to set the HBITMAP to a value that is secure to delete. Like delete nullptr.
Is there some kind of NULL Handle in Windows? If I create a bmp
Share
Bad news first. For historic reasons, there is no generally valid “invalid handle” value in the Windows API. Different subsystems in Windows consider either
NULLorINVALID_HANDLE_VALUEas the invalid handle value (both for returning an invalid handle value and for taking one). Related article on Old New Thing.However, the good news is that although you still need to be prepared for unexpected return values (unless you dig through the documentation for every single function you use), providing either invalid value still always “works” in practice.
You might not have used the correct designated “invalid” value, but it’s still invalid, and thus the function will fail. Your application will not crash, there are no negative consequences other than having wasted a few CPU cycles.
Therefore, go ahead and use
NULL(ornullptr), you’re good with that. If nothing else, it’s intuitive for someone reading your code later. In your concrete example, it’s also the correct thing, since GDI functions assumeNULLas invalid.You can pretty much rely that both
NULLandINVALID_HANDLE_VALUEare invalid values. Although I’m not aware of a requirement (as in, explicitly stated in the documentation) that a validHANDLEmust be non-zero, in practice they always are. I’m willing to bet you will not find a handle with the value zero, ever (just try and use Sysinternals’handletool, no single process on your computer will probably have a handle lower than 20).But even assuming that
NULLcan be a valid handle value, you have to consider that some handles are already opened and closed even beforemainis called or global constructors are run, you really don’t have a choice. That means that assumingNULLcould be a valid handle, and asssuming it was still valid at the time your program runs, the chance that this hypothetical handle is incidentially of a type compatible with the API function is very low.On the other hand, one might argue that an application might have
(unsigned) -1handles open, renderingINVALID_HANDLE_VALUEa valid value.Unless you are leaking handles, I cannot imagine how you would ever get that many open handles. But more importantly, long before hitting that number, you’ll probably run out of memory on a 64 bit system, and you’ll definitively run out of address space on a 32 bit system.
If
INVALID_HANDLE_VALUEbeing a valid handle ever becomes an issue, you have a much more serious problem.