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 is very tempting to simply insert a HANDLE into shared_ptr (for example:) shared_ptr<void> handle (CreateFile(args),&CloseHandle)so that the handle is closed. My only problem with this quick and easy way to do RAII is if CreateFile can return NULL as a HANDLE value.

+5
source share
3 answers

NULLis not a valid descriptor value. You may notice this because some Windows API functions return NULLto indicate a failure. Since there is one function to remove descriptors CloseHandle, it follows that NULLit is not a valid value HANDLE. Therefore, CreateFileit can never return NULL.

Raymond Chen wrote a blog article about this topic: Why does HANDLE return values ​​so inconsistently? .

Now I do not know anything about shared_ptr<>, so I do not want to comment on whether your idea is suitable. I am simply answering the direct question that you asked.

+6
source

NULL, INVALID_HANDLE_VALUE.

, RAII - , CreateFile NULL. , HANDLE , , .

, , HANDLE, , .

+1

CreateFile never returns NULL. I suggest you use the already created shell ATL::CAtlFileand not use the new version based on shared_ptr.

0
source

All Articles