这会正确释放数据吗?

Will this Free the data correctly?

本文关键字:数据 释放      更新时间:2023-10-16

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

伪代码:
std::map<std::string, ClassPointer*>::iterator tempIterator;
    for(tempIterator = directory.begin(); tempIterator < directory.end; 
        tempIterator++)
        delete &tempIterator;

由于目录存储了原始指针,因此在必要时删除这些指针是您的责任。

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;

如果ClassPointer*new[]被分配,这段代码可能无法正常工作。使用智能指针是一个更好的主意。

供参考,应该是

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

正确的做法是:

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;

,顺便说一句,这只会释放一个类指针,而不是一个映射元素!(因此映射中的指针无效,但item仍然在映射中)