使用指针在地图中释放内存

时间:2013-04-04 03:14:02

标签: c++ stl

我试图从地图中删除指针元素(地图中的值是一个指针),我在这里看到了代码What happens to an STL iterator after erasing it in VS, UNIX/Linux?

for(map<T, S*>::iterator it = T2pS.begin(); it != T2pS.end(); T2pS.erase(it++)) {
    // wilhelmtell in the comments is right: no need to check for NULL. 
    // delete of a NULL pointer is a no-op.
    if(it->second != NULL) {
        delete it->second;
        it->second = NULL;
    }
}

我不确定'删除它 - &gt;秒'是否取消分配正确的内存,因为擦除(it ++)步骤已经将迭代器移动到下一个对象。到达delete语句时,它指向我们不想删除的下一个元素。我错过了什么吗?

2 个答案:

答案 0 :(得分:2)

我相信这会按预期运作。

for循环的第三部分(迭代器被擦除然后递增)在第一次迭代之后执行,依此类推每个相关的迭代。因此,您总是在循环内容中删除已经“处理过”的元素。

一个平行的例子:

for (int i = 0; i < 1; ++i) { ...

在递增i = 0并检查循环条件之前,您仍将进入循环并使用i执行。

答案 1 :(得分:1)

您可能想尝试其他方式:

while (T2pS.size() > 0) {
  if (T2pS.begin()->second != NULL) {
    delete T2pS.begin()->second;
  }
  T2pS.erase(T2pS.begin());
}