問題描述
通過簡單地編寫 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)
?
推薦答案
你可以;空指針被隱式轉換為布爾值 false 而非空指針被轉換為 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:
算術、無作用域枚舉、指針或指向成員類型的指針的純右值可以轉換為類型的純右值布爾
.零值、空指針值或空成員指針值被轉換為假
;任何其他值都轉換為真
.類型的純右值std::nullptr_t
可以轉換為純右值類型bool
;結果值是假
.
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 (pointer) 而不是 if (pointer != NULL) 嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!