如何从一个集合中释放内存
我有一个包含指向已分配内存的指针的集合,我使用clear方法forexample: setname.clear();
和集合本身正在被清除和他的指针,但我仍然得到内存泄漏,因为分配的内存保持未清除由于某些原因。
I got a set that includes pointers to an allocated memory, I am using the clear method forexample : setname.clear();
and the set itself is getting cleared and his pointers but I still get memory leaks because the allocated memory stays uncleared for some reason.
std :: set 的 clear()方法从集合中删除元素。但是,在你的case set包含被删除的指针,但它们指向的内存不被释放。您必须在调用 clear()
之前手动执行此操作,例如:
std::set's clear() method does remove elements from the set. However, in your case set contains pointers that are being removed, but the memory they point to is not released. You have to do it manually before the call to clear()
, for example:
struct Deleter
{
template <typename T>
void operator () (T *ptr)
{
delete ptr;
}
};
for_each (myset.begin (), myset.end (), Deleter());
Boost ,名为指针解决这个问题的容器。