处理从列表中删除指向对象的指针的"healthy"方法是什么?

What is the "healthy" way to handle deletion of pointers to objects from a list?

本文关键字:指针 healthy 方法 是什么 对象 列表 删除 处理      更新时间:2023-10-16

假设我们有一个Buyer类。

Buyer具有email数据成员和getEmail()成员函数。

此外,我们还有一个类似于下面的方法,它从指向Buyer对象的指针列表中删除指向Buyer对象的指针

void removeBuyer(Buyer* b){
list<Buyer*> :: iterator z;
for(z = buyersList.begin(); z != buyersList.end(); ){//buyersList is the list of pointers to Buyer objects
if( (*z)->getEmail() == b->getEmail() ){
z = buyersList.erase(z); 
}
else
++z;
}

然后,假设我尝试使用我刚刚删除其指针的Buyer对象"登录"。

void logIn{
cout<<"Give email"<<endl;
std::string e;
std::cin>>e;
list <Buyer*> :: iterator it;
for(it = buyersList().begin(); it != buyersList().end(); ++it){
if (e == (*it)->getEmail() ){// This is where the crash eventually occurs
//something
}
}
}

这有时工作正常,有时0xC0000005返回时发生崩溃。

我知道buyersList(logIn内部(已更新并保存所有指针减去已删除的指针。当我取消引用迭代器it时,it然后"成为"列表的元素之一,因此是一个存在且未被删除的指针。

我知道我可能在处理刚刚删除的指针时做错了什么。 我到底错过了什么?

问题是buyersList()按值而不是按引用返回的。