STL映射:如何释放新的内存? [英] STL map : How does it free the newed memory?

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

问题描述

使用Maps new会被调用,但是不会删除..任何人都可以解释为什么会这样吗?不能调用delete()导致内存泄漏或超出范围时自动释放内存.

解决方案

地图使用raii tecnique避免资源泄漏.该映射从不保留传递给它的句柄,而是对其进行读取以使用复制构造函数进行分配,以便它可以独立删除以确保raii.这是autoptr不能与地图一起使用的原因之一.


STL地图通常会分配更大的内存块,并使用 placement-new 来构造其中包含的对象.记忆.未使用的内存通常会保留下来,并在下次插入时重新使用.当地图超出范围时,内存 被删除.

请注意,如果您想研究映射如何分配和释放内存,则可以向std :: map提供自己的分配器"模板参数类.插入后,一旦地图超出范围,内存将自动释放吗?


Using Maps new is called but no delete is caught..Can anyone explain why is that?? NOt calling erase() causes memory leak or the memory is automatically freed when it goes out of scope.

解决方案

Maps use raii tecnique to avoid resource leak. The map never keeps the handle passed to it but insread it uses copy constructor for allocation so that it can independently delete to ensure raii. This is one reason autoptr cant be used with maps.


STL maps will often allocate a larger chunk of memory and use placement-new to construct contained objects in that memory. Unused memory is then usually kept around and re-used the next time you do an insert. The memory is deleted when the map goes out of scope.

Note that you can supply your own "allocator" template argument class to std::map if you want to study how the map allocates and frees memory.


That means even if i dont call erase after insert the memory will be freed automatically as soon as map gets out of scope?


这篇关于STL映射:如何释放新的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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