我可以使用if(指针)而不是if(pointer!= NULL)? [英] Can I use if (pointer) instead of if (pointer != NULL)?
问题描述
通过简单地写 if(pointer)
或者我可以检查不是 NULL
的指针是否安全必须使用 if(pointer!= NULL)
?
Is it safe to check a pointer to not being NULL
by writing simply if(pointer)
or do I have to use if(pointer != NULL)
?
推荐答案
能够;空指针隐式转换为布尔值,而非空指针转换为true。从C ++ 11标准中,布尔转换部分:
You can; the null pointer is implicitly converted into boolean false while non-null pointers are converted into true. From the C++11 standard, section on Boolean Conversions:
算术,无范围枚举,指针或指向成员类型的指针可以转换为类型
bool
的
prvalue。零值,空指针值或空成员指针值将转换为
false
;
任何其他值转换为
true
。类型$ pr $ bstd :: nullptr_t
的prvalue可以转换为
类型的prvalue类型
bool
;结果值为
false
。
A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type
bool
. A zero value, null pointer value, or null member pointer value is converted tofalse
; any other value is converted totrue
. A prvalue of typestd::nullptr_t
can be converted to a prvalue of typebool
; the resulting value isfalse
.
这篇关于我可以使用if(指针)而不是if(pointer!= NULL)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!