简单地说,我正在通过if
语句检查两个char*是否为nullptr或为空,但我收到一条警告,说我正在取消引用一个null指针。
// mplate is a reference to a class
if ((mplate.m_plate != nullptr || mplate.m_plate[0] != ' ') || (plate != nullptr || plate[0] != ' ')) {
// Do something
}
else {
// do something else
}
所以基本上,我想在if
语句中说,如果mplate.mplate
或plate
为空,或者nullptr
这样做,否则做其他事情。
Severity Code Description Project File Line Suppression State
Warning C6011 Dereferencing NULL pointer 'make'.
Warning C6011 Dereferencing NULL pointer 'model'.
Warning C6011 Dereferencing NULL pointer 'mplate.m_plate'.
Warning C6011 Dereferencing NULL pointer 'plate'.
Warning C6011 Dereferencing NULL pointer 'plate'.
您正在执行类似的操作
if (p != nullptr || *p)
即,只有当指针为nullptr
时,才取消引用。这意味着,如果指针有效,则不执行任何操作;如果指针无效(即UB(,则取消引用。
你需要做一个逻辑and
,就像这个
if (p != nullptr && *p)
即仅在指针是而不是CCD_ 8的情况下解引用。
您的问题指出,如果指针为NULL或指向' '
,则您希望执行if
块,因此您确实想要:
// mplate is a reference to a class
if (mplate.m_plate == nullptr || mplate.m_plate[0] == ' ' || plate == nullptr || plate[0] == ' ') {
// Do something (Block entered on the FIRST true test...)
}
else {
// do something else ( Block entered ONLY if all four tests are false...)
}
在该代码中,一旦任何一个测试为true
,if
语句中的测试就会"短路",因此永远不会取消引用nullptr
。