这会正确释放数据吗?
Will this Free the data correctly?
我只是想知道这是否会正确释放数据。
伪代码: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仍然在映射中)
相关文章:
- 我可以使用哪种数据结构来释放连续内存中的内存?
- 如果一个变量在它之前释放了另一个(相同的数据类型)变量,如何将其分配给内存?
- 向量中的数据何时释放
- QTCPSOCTED数据传输在读取缓冲区已满时停止,并且在释放时不会恢复
- 如何防止ptr_map在插入失败时释放数据
- pybind11和std :: vector-如何使用胶囊释放数据
- 我试图释放数据的某些部分,并用特定的整数值标记其休息,以表明它不是有效的指针.(不是数组)
- C++ 在覆盖新运算符和删除运算符时不释放数据
- 数据结构中的双重释放或损坏
- 即使在返回值之前释放后,数据仍在指针中仍然存在
- 从 C++ 中的字符*释放数据
- 释放包含数据的缓冲区
- 当类对象完成时,是否为 C++ 类的数据成员动态分配的内存会释放
- 自动释放 Mat 中的用户数据.可能吗
- 为什么在为常量数据释放内存时需要const_cast
- 如何在运行时确定数据的大小(已分配和已释放)
- 在释放数据之前,请先将阵列填满
- opengl在调用glBufferData后释放内存会导致数据不显示
- 这会正确释放数据吗?
- 是否在释放或析构函数中删除com对象的实例数据?