Search code examples
c++windowswinapi

Can CreateFile ever return NULL?


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.


Solution

  • 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.