处理从列表中删除指向对象的指针的"healthy"方法是什么?
What is the "healthy" way to handle deletion of pointers to objects from a list?
假设我们有一个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()
按值而不是按引用返回的。
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么++(*p)更改指针值
- 调整大小后指向元素值的指针unordered_map有效?
- 正在将指针转换为范围
- 使用指向成员的指针将成员函数作为参数传递
- 将OpenCV C++重写为EmguCV C#-如何使用指针
- 处理从列表中删除指向对象的指针的"healthy"方法是什么?