CreateFile 可以返回 NULL 吗? [英] Can CreateFile ever return NULL?

查看:42
本文介绍了CreateFile 可以返回 NULL 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 CreateFile 返回的无效值是 INVALID_HANDLE_VALUE.但由于我也喜欢使用 RAII,因此很容易将 HANDLE 放在 shared_ptr 中(如下所示:shared_ptr句柄 (CreateFile(args),&CloseHandle))以确保手柄已关闭.我对这种快速简便的 RAII 方法唯一关心的是 CreateFile 是否可以返回 NULL 作为 HANDLE 值.

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 不是有效的句柄值.您可以从某些 Windows API 函数返回 NULL 以指示失败这一事实中辨别出这一点.由于只有一个处理句柄的函数 CloseHandle,因此 NULL 不是有效的 HANDLE 值.因此 CreateFile 永远不会返回 NULL.

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 写了一篇关于这个话题的博客文章:为什么 HANDLE 返回值如此不一致?.

Raymond Chen wrote a blog article touching on this topic: Why are HANDLE return values so inconsistent?.

现在,我对 shared_ptr<> 一无所知,所以我不想评论您的想法是否合适.我只是在回答你提出的直接问题.

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.

这篇关于CreateFile 可以返回 NULL 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆