测试无效的 Windows 句柄:我应该与“NULL”、“0”进行比较吗?甚至“nullptr”?

发布于 2024-09-27 14:08:01 字数 343 浏览 1 评论 0原文

我的背景是,指针通常应与“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

幸福%小乖 2024-10-04 14:08:01

将其与记录的错误返回值进行比较。这意味着您应该将其与 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).

花开柳相依 2024-10-04 14:08:01

回答你的问题: HANDLE 类型在 winnt.h 中声明为 因此

typedef PVOID HANDLE;

,从技术上来说它是一个指针。

但是,我只会使用记录的任何内容;如果文档指出返回 NULL,我就完全使用它,除非有证据表明文档不正确。

我什至没有考虑指针与整数。 NULL 只是一个不透明的值(在这种情况下),而 HANDLE 对我来说是一个不透明的类型,我懒得去查找它是什么#define< /code>'d 到。

To answer your question: the HANDLE type is declared in winnt.h as

typedef PVOID HANDLE;

Hence, 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) and HANDLE is an opaque type to me and I don't bother looking up what it is #define'd to.

霓裳挽歌倾城醉 2024-10-04 14:08:01

我认为 INVALID_HANDLE_VALUE 通常是 Windows 句柄的正确“无效”值...并且其计算结果为 -1

I think INVALID_HANDLE_VALUE is usually the proper 'invalid' value for windows handles...and that evaluates to -1.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文