本文介绍了C ++:比较C函数的返回值是否为NULL或nullptr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C ++进行编码,并使用一个C函数,该函数在发生故障的情况下将返回NULL.将其返回值与NULL或nullptr进行比较,将是正确的想法吗?

I'm coding in C++, and using a C function that returns NULL in case of a failure. What would be the correct think to do, compare its return value to NULL or nullptr?

if ((CreateEventEx(myEventHandleHere) == NULL)
{
    ...
}

if ((CreateEventEx(myEventHandleHere) == nullptr)
{
    ...
}

推荐答案

(非规范性说法):

The draft C++ standard in appendix C.4 C Standard library which is non-normative says:

各个规范部分都同意,例如18.2说:

the respective normative sections agree for example 18.2 says:

这意味着如果您正在使用那些特定的标头NULL应该与nullptr兼容,那么我只会使用nullptr.

which would mean if you are using the those particular headers NULL should be compatible with nullptr and then I would just use nullptr.

在涵盖兼容性的附录D中,似乎没有对.h头文件做出类似的陈述,因此尽管我们希望NULLnullptr应该兼容 null指针常量,如果从标准的角度来看它们不是最少的话,我们将感到惊讶.从实际的角度来看,这使我们陷入了困境.我们可以确定它们是兼容的,但是我们没有足够的标准信息来证明这一点.

In appendix D which covers compatibility does not seem to make a similar statement for .h header files, so although we would expect that NULL and nullptr should be compatible null pointer constants and we would be surprised if they were not from the standard point of view it seems at minimum to be underspecified. Which leaves us with a dilemma, from a practical perspective we are pretty sure they are compatible but we don't have enough information from the standard to prove it.

所以我将使用您正在使用的特定头文件所定义的NULL,或者我们可以使用!= 0,因为幸运的是C99和C ++ 11都告诉我们0 null指针常量.

So I would use NULL as defined by the specific header file you are using or we can use != 0 since fortunately both C99 and C++11 tell us that 0 is a null pointer constant.

从C99部分6.3.2.3 指针:

和:

和C ++部分4.10 指针转换告诉我们:

and C++ section 4.10 Pointer conversions tells us:

这篇关于C ++:比较C函数的返回值是否为NULL或nullptr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 06:38
查看更多