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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3905538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 15:23:13  来源:igfitidea点击:

Testing for an invalid windows handle: should I compare with 'NULL', '0' or even 'nullptr'?

c++windowsnullhandles

提问by Coder_Dan

I'm coming from a background whereby pointers should generally be compared with 'NULL' and integers with '0'.

我来自一个背景,即通常应该将指针与“NULL”和整数与“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'.

由于我没有将 Windows 句柄视为纯粹意义上的“指针”(即“句柄”),因此我养成了将它们与 0 而不是“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'.

无论如何,我只是注意到返回 HDC 的 CreateIC 的帮助指出,如果函数失败,则返回“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?

现在我很困惑 - 我想知道其他人的看法 - 将 Windows 句柄视为指针是否更正确(因此对于现代编译器,将其与“NULL”或“nullptr”进行检查)还是应该考虑是整数?

采纳答案by MSalters

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).

将其与记录的错误返回值进行比较。这意味着您应该将它与INVALID_HANDLE、0、-1、非零或<=32(我不是在和最后一个开玩笑,请参阅 ShellExecute)进行比较。

回答by Frerich Raabe

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

回答您的问题:该HANDLE类型在 winnt.h 中声明为

typedef PVOID HANDLE;

Hence, technically it is a pointer.

因此,从技术上讲,它是一个指针。

However, I would just use whatever is documented; if the documentation states that NULLis returned, I use exactly that unless evidence shows that the documentation is incorrect.

但是,我只会使用记录在案的任何内容;如果文档说明NULL已返回,我将完全使用该文档,除非有证据表明文档不正确。

I don't even think about pointers vs. integers. NULLis just an opaque value (in this situation) and HANDLEis an opaque type to me and I don't bother looking up what it is #define'd to.

我什至不考虑指针与整数。NULL只是一个不透明的值(在这种情况下)并且HANDLE对我来说是一个不透明的类型,我不费心去查找它是什么#define

回答by sje397

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

我认为INVALID_HANDLE_VALUE通常是 Windows 句柄的正确“无效”值......并且评估为-1.