問(wèn)題描述
在最近的代碼審查中,一位貢獻(xiàn)者試圖強(qiáng)制以下列方式對(duì)指針執(zhí)行所有 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
}
我同意他的方式更清楚一點(diǎn),因?yàn)樗鞔_表示確保此指針不為 NULL",但我會(huì)反駁說(shuō),任何正在處理此代碼的人都會(huì)理解使用指針if
語(yǔ)句中的變量隱式檢查 NULL
.另外我覺(jué)得第二種方法引入同類錯(cuò)誤的可能性較小:
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)
查找和調(diào)試絕對(duì)是一件痛苦的事情.
which is just an absolute pain to find and debug.
您更喜歡哪種方式,為什么?
Which way do you prefer and why?
推薦答案
根據(jù)我的經(jīng)驗(yàn),if (ptr)
或 if (!ptr)
形式的測(cè)試是首選.它們不依賴于符號(hào) NULL
的定義.他們不會(huì)暴露意外分配的機(jī)會(huì).它們清晰簡(jiǎn)潔.
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 在評(píng)論中指出的那樣,它們與 C++ 類(例如 auto_ptr
)兼容,這些類是充當(dāng)指針的對(duì)象并提供到 bool
來(lái)啟用這個(gè)習(xí)語(yǔ).對(duì)于這些對(duì)象,與 NULL
的顯式比較必須調(diào)用到指針的轉(zhuǎn)換,這可能具有其他語(yǔ)義副作用,或者比 bool
的簡(jiǎn)單存在檢查更昂貴轉(zhuǎn)換意味著.
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.
我更喜歡能說(shuō)明含義而沒(méi)有不需要的文本的代碼.if (ptr != NULL)
與 if (ptr)
具有相同的含義,但代價(jià)是冗余的特異性.下一個(gè)合乎邏輯的事情是編寫(xiě) if ((ptr != NULL) == TRUE)
并且這種方式是瘋狂的.C語(yǔ)言很清楚,一個(gè)由if
、while
等測(cè)試的布爾值具有特定含義,非零值為真,零為假.冗余并沒(méi)有讓它更清楚.
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.
這篇關(guān)于在 C/C++ 中檢查空指針的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!