[英]C++ - What is the most efficient way to test null pointer?
What is most efficient between the two ways of testing pointer nullity : if(pointer==NULL)
or if(!pointer)
. 在测试指针无效性的两种方法之间最有效的方法是:
if(pointer==NULL)
或if(!pointer)
。
MyObject* p;
[...]
// Solution 1
if ( p )
{ // Do something
}
// Solution 2
if ( p!=NULL )
{ // Do something
}
It makes no difference what so ever. 没什么区别。 It's purely a style issue what you prefer.
您偏爱的纯粹是样式问题。
By the way, you should use nullptr
rather than NULL
if you use C++11 or later. 顺便说一句,如果使用C ++ 11或更高版本,则应使用
nullptr
而不是NULL
。
I prefer if (ptr)
because: 我更喜欢
if (ptr)
因为:
NULL
keyword. NULL
关键字。 Which have to be nullptr
on C++11 or later as Jesper Juhl mentioned . nullptr
。 They are compatible with C++ classes such as auto_ptr that are objects that act as pointers and which provide a conversion to bool to enable exactly this idiom.
它们与诸如auto_ptr之类的C ++类兼容,这些类是充当指针的对象,并提供对bool的转换以完全启用此惯用语。 For these objects, an explicit comparison to NULL would have to invoke a conversion to pointer which may have other semantic side effects or be more expensive than the simple existence check that the bool conversion implies.
对于这些对象,与NULL的显式比较将不得不调用对指针的转换,该转换可能具有其他语义副作用,或者比bool转换所暗示的简单存在检查更为昂贵。
Those are same. 那些都是一样的。 It makes no change in your program whatever you use.
无论您使用什么程序,都不会改变程序。
I'd rather prefer the if (p!=NULL)
as it prevents form accidental errors like casting the p
in other thing, like an int
for instance, between the declaration and the use of it. 我宁愿使用
if (p!=NULL)
因为它可以防止出现形式错误,例如在声明和使用之间将p
强制转换为其他东西,例如int
。
Here the compiler should warn as int differ form NULL
(initially NULL=(void*)0
) 在此,编译器应发出警告,因为int与
NULL
形式不同(最初是NULL=(void*)0
)
Furthermore i prefer to declare like this : 此外,我更喜欢这样声明:
MyObject* p=NULL;
because you cannot assure that p
wont have a value different of zéro. 因为您不能确保
p
不会具有与zéro不同的值。 If you miss to instantiate it between declaration and use. 如果您错过了在声明和使用之间实例化它的方法。
And it is less misleading than the if (p==NULL){} else {}
which may occur in an accidental assignment (only one =) 而且它比偶发赋值中可能发生的
if (p==NULL){} else {}
误导性(仅一个=)
Off course in the C++11 or later this could involve some changes in your code even if the call of NULL
is still working but deprecated. 在C ++ 11或更高版本中,这当然可能涉及代码中的某些更改,即使
NULL
调用仍然有效但已被弃用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.