STL的第一级配置器
考虑到复杂度问题,没有实现异常处理.
学习STL主要目的之一是为了学习内存管理
1 #ifndef __H_MALLOC 2 #define __H_MALLOC 3 #include <stdlib.h> 4 #include <cstddef> 5 #include <iostream> 6 using namespace std; 7 template<int inst> 8 class __malloc_alloc_template 9 { 10 private: 11 /* 以下函数用于处理内存不足的情况 */ 12 static void* oom_malloc(size_t); 13 static void* oom_realloc(void *, size_t); 14 // define a pointer to a function (passed void) return void 15 static void (* __malloc_alloc_oom_handler)(); 16 17 public: 18 19 static void* allocate(size_t n) 20 { 21 void* result = malloc(n); 22 // 无法满足需求时,改用 oom_malloc(n) 23 if(result == 0) 24 result = oom_malloc(n); 25 return result; 26 } 27 28 29 static void deallocate(void* p, size_t /* n */) 30 { 31 free(p); 32 } 33 34 static void* reallocate(void* p, size_t /* old_sz */, size_t new_sz) 35 { 36 void* result = realloc(p, new_sz); 37 // 无法满足需求时,改用 oom_realloc() 38 if(result == 0) 39 result = oom_realloc(p, new_sz); 40 return result; 41 } 42 43 static void (* set_malloc_handler(void (*f)()))() 44 { 45 void (* old)() = __malloc_alloc_oom_handler; 46 __malloc_alloc_oom_handler = f; 47 return old; 48 } 49 }; 50 51 // malloc_alloc out-of-memory handing 52 template<int inst> 53 void(* __malloc_alloc_template<inst>::__malloc_alloc_oom_handler)() = 0; 54 55 template <int inst> 56 void * __malloc_alloc_template<inst>::oom_malloc(size_t n) 57 { 58 // define a pointer to a function (passed void) return void 59 void (* my_alloc_hander)(); 60 void* result; 61 62 for(;;) 63 { 64 my_alloc_hander = __malloc_alloc_oom_handler; 65 if(0 == my_alloc_hander) 66 { 67 cout<< "out of memory" << endl; 68 } 69 70 (*my_alloc_hander)(); // 调用处理例程,企图释放内存 71 result = malloc(n); // 再次尝试配置内存 72 if(result) 73 return result; 74 } 75 } 76 77 78 template<int inst> 79 void * __malloc_alloc_template<inst>::oom_realloc(void* p, size_t n) 80 { 81 // define a pointer to a function (passed void) return void 82 void (* my_alloc_hander)(); 83 void* result; 84 85 for(;;) 86 { 87 my_alloc_hander = __malloc_alloc_oom_handler; 88 if(0 == my_alloc_hander) 89 { 90 cout << "out of memory" << endl; 91 } 92 93 (*my_alloc_hander)(); // 调用处理例程,企图释放内存 94 result = realloc(p, n); // 再次尝试配置内存 95 if(result) 96 return result; 97 } 98 } 99 100 typedef __malloc_alloc_template<0> malloc_alloc; 101 102 #endif
浙公网安备 33010602011771号