在定義良好的程式碼中,address-of 欄位不能為
null
備註
address-of 運算子傳回其運算元的位址。 這個值不應該與 nullptr比較:
- 如果基底指標是
nullptr,address-of 欄位只能是nullptr,而且欄位位於零位移 (&p->field == nullptr意指p == nullptr)。 在此情況下,應該簡化運算式。 - 在任何其他情況下,除非程式碼中有未定義的行為,否則一元
&運算子的值不能是nullptr(&v == nullptr一律計算結果為 false)。
範例
下列範例會產生 C6398:
struct A { int* x; };
bool hasNullField(A *a)
{
return &a->x == nullptr; // C6398 reported here.
}
若要修正此問題,請仔細檢查是否刻意使用一元 &:
struct A { int* x; };
bool hasNullField(A *a)
{
return a->x == nullptr; // no C6398 reported here.
}