这会正确释放数据吗?

时间:2013-01-21 04:03:54

标签: c++ memory iterator memory-leaks allocation

我只是想知道这是否能正确释放数据。

伪代码:

std::map<std::string, ClassPointer*>::iterator tempIterator;

    for(tempIterator = directory.begin(); tempIterator < directory.end; 
        tempIterator++)
        delete &tempIterator;

3 个答案:

答案 0 :(得分:4)

当目录存储原始指针时,您有责任在必要时删除这些指针。

std::map<std::string, ClassPointer*>::iterator tempIterator;

for(tempIterator = directory.begin(); tempIterator < directory.end(); 
    tempIterator++)
{
    delete tempIterator->second;
}

总是,更好的解决方案是在STL容器中使用智能指针:

 std::map<std::string, std::shared_ptr<ClassPointer>> directory;

答案 1 :(得分:2)

如果ClassPointer*分配了new[],则此段代码可能无法正常运行。使用智能指针是一个更好的主意。

而且仅供参考,它应该是

for (auto tempIterator = directory.begin(); tempIterator != directory.end(); 
    ++tempIterator)

答案 2 :(得分:1)

正确的方法是:

for (
    std::map<std::string, ClassPointer*>::iterator it = directory.begin()
  , last = directory.end()     // avoid call to end() every time
  ; it != last                 // use operator != (NOT operator <)
  ; ++it                       // prefer prefix increment for iterators!
  ) delete it->second;         // iterator points to std::pair actually!

或C ++ 11方式:

for (auto& item : directory) delete item.second;

和BTW,这只会释放一个类指针,而不是一个map元素! (因此地图中的指针变为无效,但项目仍保留在地图中)