C++ 无序映射:clear()不释放clear()上的堆

C++ 无序映射:clear()不释放clear()上的堆,c++,memory-leaks,heap-memory,unordered-map,dynamic-allocation,C++,Memory Leaks,Heap Memory,Unordered Map,Dynamic Allocation,我在Solaris 10上使用g++4.9.2使用无序_映射,但令人惊讶的是,我发现clear()并没有释放heap。 以下是示例代码: #include <iostream> #include <unordered_map> int main () { std::unordered_map<long long, long long> mymap; mymap.rehash(200000); getchar(); for (int i = 0

我在Solaris 10上使用g++4.9.2使用无序_映射,但令人惊讶的是,我发现clear()并没有释放heap。 以下是示例代码:

#include <iostream>
#include <unordered_map>

int main ()
{
  std::unordered_map<long long, long long> mymap;
  mymap.rehash(200000);
  getchar();
  for (int i = 0; i < 2000000; i++) {
    mymap[i] = i*i;
  }
  std::cout << "current bucket_count: " << mymap.bucket_count() << std::endl;
  std::cout << "current size: " << mymap.size() << std::endl;
  getchar();
  mymap.clear();
  std::cout << "current bucket_count: " << mymap.bucket_count() << std::endl;
  std::cout << "current size: " << mymap.size() << std::endl;
  getchar();
  return 0;
}
这表明(步骤3),clear()对堆没有影响。尽管文件上说

std::unordered_map::clear
void clear() noexcept;
Clear content
All the elements in the unordered_map container are dropped: their destructors are called, and they are removed from the container, leaving it with a size of 0.
但是,我的堆计数并没有反映这一点。 有没有其他方法释放无序的_映射对象占用的堆?或者,我应该用别的东西吗?
请指导如何从无序地图中释放内存?

地图内容已被擦除。与磁盘中的文件类似(仅从索引中删除)。如果下次可以使用内存,释放内存是无效的

如果你不能真正释放地图内存,你需要销毁整个对象。或者您可以尝试调用
void reserve(大小\类型计数)为零。(我还没试过)

无序映射:clear()不释放clear()上的堆

C++标准不要求<代码>清除>代码>释放内存。< /P> 但是,我的堆计数并没有反映这一点

文档中没有提到堆。元素的析构函数被调用,正如您确认的,大小为0。如果添加新元素,它们可能会重用先前清除的元素所使用的内存

有没有其他方法释放无序的_映射对象占用的堆

销毁地图肯定会释放其所有内存

mymap.rehash(0)
也可能有效

然而,仅仅因为内存被释放到实现中(通过调用
free
),并不意味着实现必然会将内存释放到操作系统中。实现可能会决定将内存重新用于其他分配(不过,这仅适用于较小的分配)


<> P>在C++中没有标准的方法,但是Linux提供了一个函数<代码> MalCuxTrim< /Cord>,它将<强>尝试-//St>将释放的内存从堆的顶部释放到OS。< /P> < P>内存不释放,因为该映射应该继续使用,直到它超出范围或被删除。对于这个合理的默认用例,重新分配将导致不必要的开销。我的建议是:

  • 如果确实不再需要它,将其范围限制在需要它的地方,分别使用具有适当范围的映射的智能指针
  • 如果您仍然需要它,但不是暂时需要,或者只需要更少的元素,
    swap
    使用一个空的临时映射(随后将被删除)
  • 显式调用析构函数并在适当位置重新创建一个新映射

您在“文档”中的引用并没有提到释放映射内部使用的内存,只是映射将变为空。显然是这样的(因为打印的大小是零)。我认为您必须理解大小和容量之间存在差异,它不会释放底层数据结构,即使它确实释放了用于所包含元素的内存。当您调用清除时,它可能调用析构函数,并将一些大小变量设置为0,但不释放容器所保存的内存。已经从操作系统获取内存以响应<代码>新< /Cord>调用,C++运行库将不会释放它直到进程结束。保留(0)可能不起作用,因为它不具有约束力,并且保留值将小于容量。
std::unordered_map::clear
void clear() noexcept;
Clear content
All the elements in the unordered_map container are dropped: their destructors are called, and they are removed from the container, leaving it with a size of 0.