假設我有一個指針:int *pointer
。檢查指針的可空性:!指針或指針== nullptr?
bool nullability = !pointer;
或用:
如果我想測試它是否爲空,應該我做
bool nullability = (pointer == nullptr);
都表達相同呢? 如果沒有,爲什麼和什麼是副作用?
假設我有一個指針:int *pointer
。檢查指針的可空性:!指針或指針== nullptr?
bool nullability = !pointer;
或用:
如果我想測試它是否爲空,應該我做
bool nullability = (pointer == nullptr);
都表達相同呢? 如果沒有,爲什麼和什麼是副作用?
兩者都是equivaluent,因爲nullptr
保證在轉換爲布爾值時轉換爲false
。
從N4296:
4.12布爾轉換
算術,無作用域枚舉,指針,或指針的prvalue到成員類型可以 轉換爲bool類型的prvalue。零值,空指針值, 或空成員指針值被轉換爲false;任何其他值爲 轉換爲true。對於直接初始化(8.5),類型 std :: nullptr_t的prvalue可以轉換爲類型爲bool的prvalue; 結果值是錯誤的。
根據標準,這答案(Implicit cast of null pointer to bool)兩個語法都有相同的行爲
看到這裏的一些想法http://stackoverflow.com/a/17774781/133203 –