测试无效的 Windows 句柄:我应该与“NULL”、“0”进行比较吗?甚至“nullptr”?
我的背景是,指针通常应与“NULL”进行比较,整数应与“0”进行比较。
由于我并不认为 Windows 句柄是纯粹意义上的“指针”(即“句柄”),因此我养成了将它们与 0 而不是“NULL”进行比较的习惯。
显然,现在它们在内部实现为指针,但我个人认为这仅仅是为了获得某种类型安全性,而不是因为它们本质上是指针。
无论如何,我只是注意到返回 HDC 的 CreateIC 的帮助指出,如果函数失败,则返回“NULL”。
现在我很困惑 - 并且想知道其他人的看法 - 将 Windows 句柄视为指针是否更正确(因此针对现代编译器将其与“NULL”或“nullptr”进行检查),或者应该将其视为是一个整数吗?
I'm coming from a background whereby pointers should generally be compared with 'NULL' and integers with '0'.
Since I didn't perceive Windows handles to be 'pointers' in the pure sense (being 'handles'), I'd got into the habit of comparing them with 0 rather than 'NULL'.
Clearly they're implemented internally as pointers nowadays, but I personally consider that to be merely for acquiring some type-safety rather than because they are intrinsically pointers.
Anyway, I just noticed that the help for CreateIC which returns an HDC states that if the function fails then it returns 'NULL'.
Now I'm confused - and am wondering what other people reckon - is it more correct to consider a Windows handle to be a pointer (and therefore check it against 'NULL' or 'nullptr' for modern compilers) or should it be considered to be an integer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将其与记录的错误返回值进行比较。这意味着您应该将其与
INVALID_HANDLE
、0、-1、非零或<=32
进行比较(我不是在跟最后一个开玩笑,请参阅外壳执行)。Compare it against the documented error return value. That means that you should compare it against
INVALID_HANDLE
, 0, -1, non-zero, or<=32
(I'm not kidding with the last one, see ShellExecute).回答你的问题:
HANDLE
类型在 winnt.h 中声明为 因此,从技术上来说它是一个指针。
但是,我只会使用记录的任何内容;如果文档指出返回
NULL
,我就完全使用它,除非有证据表明文档不正确。我什至没有考虑指针与整数。
NULL
只是一个不透明的值(在这种情况下),而HANDLE
对我来说是一个不透明的类型,我懒得去查找它是什么#define< /code>'d 到。
To answer your question: the
HANDLE
type is declared in winnt.h asHence, technically it is a pointer.
However, I would just use whatever is documented; if the documentation states that
NULL
is returned, I use exactly that unless evidence shows that the documentation is incorrect.I don't even think about pointers vs. integers.
NULL
is just an opaque value (in this situation) andHANDLE
is an opaque type to me and I don't bother looking up what it is#define
'd to.我认为
INVALID_HANDLE_VALUE
通常是 Windows 句柄的正确“无效”值...并且其计算结果为-1
。I think
INVALID_HANDLE_VALUE
is usually the proper 'invalid' value for windows handles...and that evaluates to-1
.