如何使用boost.pool实现stl map之类的map
一开始我使用 std::map,但我需要强制映射释放内存。我只使用该地图一次并分配了大内存。该映射仅将内存返回到堆而不是操作系统,因此它仍然存在。
经过一番谷歌,我找到了 boost.pool,但我不清楚如何使用它来实现地图,谢谢!
At the beginning I use std::map, but I need to force the map to deallocate the memory. I use the map only once and has allocated large memory. The map only returns the memory to heap not to OS, so it still existed.
After some google, I found boost.pool, but I have no clear idea on how to implement a map using it, thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试使用交换技巧:
在交换中,您将创建地图对象的临时实例,交换将交换临时实例和基本实例的内容,并且临时实例将被销毁。
Try to use swap trick:
In swap you will create a temporary instance of map object,
swap
will swap the contents of the temporary instance and the base instance and the temporary instance will be destroyed.如果您编写一个自定义分配器并将其传递给映射会怎样?您的分配器可以使用 clib 的 malloc 和 free。我很确定这是在操作系统级别。
您的分配器类只需要实现此处显示的方法:http://www.cplusplus。 com/reference/std/memory/allocator/
然后,当您定义 std::map .. 时,将分配器类作为第三个模板参数传递: http://www.cplusplus.com/reference/stl/map/
例如:
此链接本书中还有一些用于制作自己的分配器的示例代码:http://www.josuttis.com/libbook/memory/myalloc.hpp.html
警告: 我认为大多数分配器不归还内存的原因对于操作系统来说,保留它以供日后使用比回馈操作系统并每次都获得更多更快;所以你可能会看到一些速度低效的情况。
编辑:还发现了这个简洁的操作方法:http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c4079
What if you write a custom allocator and pass that to the map. Your alocator could use clib's malloc and free. I'm pretty sure that's at the OS level.
Your allocator class only needs to implement the methods shown here: http://www.cplusplus.com/reference/std/memory/allocator/
Then when you define your std::map .. pass the allocator class as the 3rd template argument: http://www.cplusplus.com/reference/stl/map/
eg:
This link from this book also has some example code for making your own allocator: http://www.josuttis.com/libbook/memory/myalloc.hpp.html
Warning: I think the reason most allocators don't give memory back to the OS is that it's faster to hold on to it for later, than to give back to OS and get more every time; so you might see some speed inefficiencies.
Edit: Also found this neat looking howto: http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c4079