使用原始指针删元素后,需手动清理存储迭代器的tempList吗?
问题描述
我有一项任务,必须使用提供的带原始指针的函数,根据特定条件删除std::list容器中的对象。
例如,我拥有std::list<A*> myList,需要有条件地调用函数deleteA:
void deleteA(A* a) { mylist.remove(a); delete a; }
我知道这种做法很糟糕,应该使用智能指针,但这是任务要求。由于我仅需在条件为真时移除myList的元素,想不到用lambda遍历容器并删除元素的方法,因此我采用如下解决方案:
std::list<std::list<A*>::const_iterator> tempList; auto it = myList.begin(); while (it != myList.end()) { if ((*it)->deleteCondition()) tempList.push_back(it); ++it; } if (tempList.size() > 0) { auto tempIt = tempList.begin(); while (tempIt != tempList.end()) { deleteA(*(*tempIt)); ++tempIt; } }
我的问题是:我需要清理tempList吗?函数deleteA已经销毁了迭代器指向的对象,STL容器应该会自行清理,对吗?
解答
不需要手动清理tempList,原因如下:
tempList是存储迭代器的STL容器,当它的生命周期结束(比如离开当前代码块)时,容器会自动销毁内部存储的所有迭代器对象,无需手动执行清理操作。- 调用
deleteA后,myList.remove(a)会移除对应元素,导致tempList中指向该元素的迭代器失效,但这并不影响tempList的自动清理——因为tempList销毁时只是处理迭代器本身,不会再去访问失效迭代器指向的元素,所以不会产生问题。
内容的提问来源于stack exchange,提问作者Aleksandar Demić
相关产品推荐
相关产品推荐

