RT,只能分配固定大小内存的分配器,优点是分配回收只要O(1)
template <typename T>class Alloctor{ private: typedef T* address; T *memory; size_t total_size; public: Alloctor(size_t size = 120) :memory(NULL),total_size(size){ assert(sizeof(T) >= 4); memory = (address)malloc(total_size*sizeof(T)); void * buf; for (size_t i = 0; i < total_size - 1; i++){ buf = (void*)(memory + i + 1); memcpy(memory + i, &buf,sizeof(void*)); } buf = NULL; memcpy(memory+total_size-1,&buf,sizeof(void*)); } address alloc(){ address res; memcpy(&res, memory, sizeof(void*)); memcpy(memory, res, sizeof(void*)); return res; } void free(address a){ memcpy(a, memory, sizeof(void*)); void * buf = a; memcpy(memory,&buf,sizeof(void*)); } ~Alloctor(){ free(memory); } };
时间: 2024-12-28 08:49:28