STL内存管理
1.map和set中内存释放用swap,但是进程并没有释放内存
是不是STL容器自己的内存管理机制没有释放内存给操作系统?
做实验,代码如下:
#include <stdio.h> #include <stdlib.h> #include <set> #include <map> #include <string> #include <unistd.h> using namespace std; class M1 { public: static void *getMem(int size) { return malloc(size); } static void putMem(void *ptr) { return free(ptr); } }; class M2 { public: static void *getMem(int size) { // return malloc(size); return (void *)new char[size]; } static void putMem(void *ptr) { // return free(ptr); return delete []((char *)ptr); } }; template <typename T, typename M> class MyAllc : public allocator<T> { public: typedef size_t size_type; typedef typename allocator<T>::pointer pointer; typedef typename allocator<T>::value_type value_type; typedef typename allocator<T>::const_pointer const_pointer; typedef typename allocator<T>::reference reference; typedef typename allocator<T>::const_reference const_reference; pointer allocate(size_type _Count, const void* _Hint = NULL) { _Count *= sizeof(value_type); void *rtn = M::getMem(_Count); return (pointer)rtn; } void deallocate(pointer _Ptr, size_type _Count) { M::putMem(_Ptr); } template<class _Other> struct rebind { // convert this type to allocator<_Other> typedef MyAllc<_Other, M> other; }; MyAllc() throw() {} /*MyAllc(const MyAllc& __a) throw() * : allocator<T>(__a) * {}*/ template<typename _Tp1, typename M1> MyAllc(const MyAllc<_Tp1, M1>&) throw() {} ~MyAllc() throw() {} }; int test_map() { printf("test do\n"); map<int, string, less<int >, MyAllc<int, M1> > mymap; // map<int, string > mymap; for (int i = 0 ; i< 1024*1024*10; i++) { mymap.insert ( std::pair<int,string>(i,"asdfasdf235rsdfasdfasdfasdfqwaefasdfasdfasdfasdfasdfsssssssssssssssssssss") ); } printf("test done\n"); } #define N_SIZE (1024*1024*10) int *data[N_SIZE] = {0}; int test_new() { for(int i = 0 ;i < N_SIZE;i++) { data[i] = new int[10]; for (int j = 0 ;j < 10;j++) { data[i][j] = 1; } } printf("sleep 30\n"); sleep(30); for(int i = 0 ;i < N_SIZE;i++) delete []data[i]; } int main() { printf("do\n"); test_new(); // test_map(); printf("done\n"); printf("sleep\n"); sleep(10000); }
实验1
使用map自己定义的内存适配器test_map函数和
直接用new的test_new函数做对比
发现2个程序在test_map和test_new执行完之后内存占用一直没下来,怀疑应该是操作系统的内存管理机制?
实验2
使用new和delete在map_new中把119和120行代码修改为
119 data[i] = new int[1024];
120 for (int j = 0 ;j < 1024;j++)
在test_new执行完之后,程序的内存占用下来了。
结论:操作系统内存管理机制,大块内存当即释放,小的内存不是当即释放的。