如何从一个集合中释放内存 [英] how to free memory from a set

查看:533
本文介绍了如何从一个集合中释放内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含指向已分配内存的指针的集合,我使用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 ,名为指针解决这个问题的容器

这篇关于如何从一个集合中释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆