問題描述
在最近的代碼審查中,一位貢獻者試圖強制以下列方式對指針執行所有 NULL
檢查:
In a recent code review, a contributor is trying to enforce that all NULL
checks on pointers be performed in the following manner:
int * some_ptr;
// ...
if (some_ptr == NULL)
{
// Handle null-pointer error
}
else
{
// Proceed
}
代替
int * some_ptr;
// ...
if (some_ptr)
{
// Proceed
}
else
{
// Handle null-pointer error
}
我同意他的方式更清楚一點,因為它明確表示確保此指針不為 NULL",但我會反駁說,任何正在處理此代碼的人都會理解使用指針if
語句中的變量隱式檢查 NULL
.另外我覺得第二種方法引入同類錯誤的可能性較小:
I agree that his way is a little more clear in the sense that it's explicitly saying "Make sure this pointer is not NULL", but I would counter that by saying that anyone who's working on this code would understand that using a pointer variable in an if
statement is implicitly checking for NULL
. Also I feel the second method has a smaller chance of introducing a bug of the ilk:
if (some_ptr = NULL)
查找和調試絕對是一件痛苦的事情.
which is just an absolute pain to find and debug.
您更喜歡哪種方式,為什么?
Which way do you prefer and why?
推薦答案
根據我的經驗,if (ptr)
或 if (!ptr)
形式的測試是首選.它們不依賴于符號 NULL
的定義.他們不會暴露意外分配的機會.它們清晰簡潔.
In my experience, tests of the form if (ptr)
or if (!ptr)
are preferred. They do not depend on the definition of the symbol NULL
. They do not expose the opportunity for the accidental assignment. And they are clear and succinct.
正如 SoapBox 在評論中指出的那樣,它們與 C++ 類(例如 auto_ptr
)兼容,這些類是充當指針的對象并提供到 bool
來啟用這個習語.對于這些對象,與 NULL
的顯式比較必須調用到指針的轉換,這可能具有其他語義副作用,或者比 bool
的簡單存在檢查更昂貴轉換意味著.
As SoapBox points out in a comment, 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. 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.
我更喜歡能說明含義而沒有不需要的文本的代碼.if (ptr != NULL)
與 if (ptr)
具有相同的含義,但代價是冗余的特異性.下一個合乎邏輯的事情是編寫 if ((ptr != NULL) == TRUE)
并且這種方式是瘋狂的.C語言很清楚,一個由if
、while
等測試的布爾值具有特定含義,非零值為真,零為假.冗余并沒有讓它更清楚.
I have a preference for code that says what it means without unneeded text. if (ptr != NULL)
has the same meaning as if (ptr)
but at the cost of redundant specificity. The next logical thing is to write if ((ptr != NULL) == TRUE)
and that way lies madness. The C language is clear that a boolean tested by if
, while
or the like has a specific meaning of non-zero value is true and zero is false. Redundancy does not make it clearer.
這篇關于在 C/C++ 中檢查空指針的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!