I know that the invalid value returned by CreateFile is INVALID_HANDLE_VALUE. But since I also like to use RAII it's very tempting to just stick the HANDLE in a shared_ptr (like this:
shared_ptr<void> handle (CreateFile(args),&CloseHandle))
to make sure that the handle is closed.
My only concern with this quick and easy way to do RAII is if CreateFile can return NULL as the HANDLE value.
3 Answers
NULL is not a valid handle value. You can discern this from the fact that some Windows API functions return NULL to indicate a failure. Since there is a single function to dispose of handles, CloseHandle, it follows that NULL is not a valid HANDLE value. Hence CreateFile cannot ever return NULL.
Raymond Chen wrote a blog article touching on this topic: Why are HANDLE return values so inconsistent?.
Now, I know nothing about shared_ptr<> so would like to make no comment on whether or not your idea is appropriate. I am merely answering the direct question that you asked.
When testing a HANDLE for validity in a generic way, check for both NULL and INVALID_HANDLE_VALUE.
But I don't see how RAII has anything to do with whether CreateFile can return NULL. You will need to provide custom code for testing validity and deallocating in order to make HANDLE work with a shared pointer, so you are in control of these checks, not the shared pointer class.
In other words, it makes no difference whether it's in a shared pointer or you use a normal HANDLE, the checks are exactly the same, and you must provide them either way.
shared_ptrunless you really need it to be shared. It's a huge overkill (shared_ptrinternally allocates an extra memory on the heap for reference counting), plus you'll not have a convenient access, such as a direct casting toHANDLE, becauseshared_ptrdeliberately prevents this. - valdoCloseHandleworks just fine in presence of null (not quite as silently asdelete, but still).GetLastErrorwill return 0x06 afterwards, and if you're running in the debugger, it will break on the exception, but who cares. After all it is an error, so that's good behaviour. It's not likeCloseHandle(0)means the end of the world. - Damon