简体   繁体   中英

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.

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM