Reputation: 2109
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.
Upvotes: 7
Views: 3185
Reputation: 612794
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.
Upvotes: 8
Reputation: 7189
CreateFile never returns NULL
. I suggest you to use already created wrapper ATL::CAtlFile
and don't envent a new one based on shared_ptr
.
Upvotes: 0
Reputation: 36896
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.
Upvotes: 1