Simulating the freelist in STL, there is this thought.
Union obj{Union obj* Next; Char p[1]; };class memorypool{Public:memorypool () {Union obj* temp; M_memory.assign (5, (Union obj*) NULL); for (int i=0;i<m_memory.size (), i++) {for (int j=0;j<m_memory.size (); j + +) {temp = (obj*) malloc (sizeof (char) * (1<< (i+3))); Temp->next = M_memory[i]; M_memory[i] = temp; }}} char* mem_get (int size) {int J; if (Size > $) {char* start = (char*) malloc (sizeof (char) *size); return start; } int index = freelist_index (size); obj* temp = M_memory[index]; if (temp = = NULL)//{for (J = Index+1;j<m_memory.size (); j + +) {temp = M_memory[j]; if (temp! = NULL) {M_memory[j] = temp->next; Break }} if (j>= m_memory.size ()) {for (int j=0;j <m_memory.size (); j + +) {temp = (obj*) malloc (sizeof (char) * (1<< (index+3))); Temp->next = M_memory[index]; M_memory[index] = temp; } temp = M_memory[index]; M_memory[index] = temp->next; return (char*) temp; } else {obj* cur; int up_size = round_up (size); for (int i=0;i< (1<< (J-index)); i++) {CUR = temp; Cur->next = M_memory[index]; M_memory[index] = cur; temp = cur+up_size; } temp = M_memory[index]; M_memory[index] = temp->next; return (char*) temp; }} else {M_memory[index] = temp->next; return (char*) temp; }} void Mem_free (void* p,int size) {if (Size > 128) { Free (p); return; } obj* temp = (obj*) p; int index = freelist_index (size); Temp->next = M_memory[index]; M_memory[index] = temp; } private:enum {_align = 8};//int freelist_index (int __bytes) { RetuRN (((__bytes) + (int) _align-1)/(size_t) _align-1); } int round_up (int __bytes) {return (((__bytes) + (int) _align-1) & ~ ((int) _ ALIGN-1)); } vector<union obj*> m_memory; };
Implementing a memory pool-managed class