Mercurial > hg > Members > kono > Cerium
view include/TaskManager/memorypool.h @ 70:178459e03f5c
*** empty log message ***
author | gongo |
---|---|
date | Mon, 18 Feb 2008 01:13:00 +0900 |
parents | 2356238ebea7 |
children |
line wrap: on
line source
#ifndef MEMORY_POOL_H_ #define MEMORY_POOL_H_ #include <memory> #include <stdlib.h> const int DEFAULT_EXPAND_SIZE = 32; template <class T_, size_t size_ =DEFAULT_EXPAND_SIZE> class MemoryPool { public: typedef MemoryPool<T_, size_> self_type; MemoryPool(void) { next_ = NULL; expandTheFreeList(size_); } ~MemoryPool(void) { MemoryPool * nextPtr = next_; while (nextPtr == 0) { next_ = next_->next_; delete [] nextPtr; nextPtr = next_; } } void* alloc(size_t) { if (!next_) expandTheFreeList(size_); self_type* head = next_; next_ = head->next_; return head; } void free(void* doomed) { self_type* head = static_cast<self_type*>(doomed); head->next_ = next_; next_ = head; } private: void expandTheFreeList(int howMany); private: self_type* next_; }; template <class T_, size_t size_> void MemoryPool<T_, size_>::expandTheFreeList(int howMany) { size_t size = (sizeof(T_) > sizeof(self_type*)) ? sizeof(T_) : sizeof(self_type*); self_type* runner = (self_type*)malloc(size); next_ = runner; for (int i = 0; i < howMany; i++) { runner->next_ = (self_type*)malloc(size); runner = runner->next_; } runner->next_ = 0; } template <class T_, size_t size_ =DEFAULT_EXPAND_SIZE> class UseMemoryPool { public: void* operator new(size_t size) { return pool_->alloc(size); } void operator delete(void* doomed, size_t) { pool_->free(doomed); } public: static void initMemPool() { pool_.reset(new MemoryPool<T_, size_>); } private: static std::auto_ptr<MemoryPool<T_, size_> > pool_; }; template <class T_, size_t size_> std::auto_ptr<MemoryPool<T_, size_> > UseMemoryPool<T_, size_>::pool_; #endif // ! MEMORY_POOL_H_