使用std::map时的内存增长

Memory growth when using std::map

本文关键字:内存 std map 使用      更新时间:2023-10-16

我正在观察这段代码的内存增长。但是它应该不会显示内存增长,因为所有创建的对象都被删除了。

我已经为MyObj实现了析构函数,并且通过gdb观察到,当映射迭代时,实际上调用了析构函数。谁能解释一下我哪里做错了?

map<int,MyObj*> myMap;
for(int i = 1; i<= 500000; i ++) 
    {
        MyObj* pMyObj = new MyObj; 
        myMap.insert(pair<int,MyObj*>(i,pMyObj));
    }
map<int,MyObj*>::iterator ite = myMap.begin();
while (ite != myMap.end())
{
    delete ite->second;
    ite++;
}
myMap.clear();

您可能想要阅读http://www.gnu.org/software/libc/manual/html_node/Freeing-after-Malloc.html#Freeing-after-Malloc。尤其是最后几段:

有时候,free可以将内存返回给操作系统让这个过程更小。通常,它所能做的就是允许以后调用malloc来重用空间。与此同时,空间依然存在在你的程序中,作为malloc内部使用的自由列表的一部分。

如果您希望将大块内存返回给操作系统,请考虑使用mmap