我得到一个错误,我有一个潜在的未初始化的本地指针变量,我不确定为什么。
Link *popBck(Link *list, int &val) {
if (!list)return 0;
Link *front = list, *back;
while (front->ptr) {
back = front;
front = front->ptr;
}
val = front->data;
delete front;
back->ptr = 0;
return list;
}
答案 0 :(得分:0)
您无需在此处初始化back
:
Link *front = list, *back;
,由于对back
的唯一赋值是有条件的,因此可能无法执行:
while (front->ptr) { // This condition could be false...
back = front; // ... in which case this doesn't happen.
front = front->ptr;
}
这将导致您在此处取消引用未初始化的back
:
back->ptr = 0;
始终初始化变量是一个好主意。
对于单例列表,您还需要一种特殊情况,即应返回空指针。
如果您将back
初始化为空指针,那么当您只有一个元素的列表时,它将完全为空。
类似这样的东西:
Link *popBack(Link *list, int &val) {
if (!list) return nullptr;
Link *front = list, *back = nullptr;
while (front->ptr) {
back = front;
front = front->ptr;
}
val = front->data;
delete front;
if (!back)
{
return nullptr;
}
else
{
back->ptr = 0;
return list;
}
}