#pragma once #include #include #include template class Alloc_Pool { private: struct NODE { NODE* next; char t[sizeof(T)]; }; public: Alloc_Pool(); ~Alloc_Pool(); //T* Alloc(); template T* Alloc(X...Args); void Free(T* ptr); static Alloc_Pool& GetInstance(); private: bool InternalAlloc(); NODE* Head; int m_BaseIndex; NODE* PtrBase[T::BASE_SIZE]; NODE* next; std::mutex lock; }; template bool Alloc_Pool::InternalAlloc() { NODE* p = NULL; if (m_BaseIndex < T::BASE_SIZE) p = PtrBase[m_BaseIndex++] = (NODE*)malloc(sizeof(NODE) * T::ALLOC_ARG); else { //p = (NODE*)malloc(sizeof(NODE)*T::ALLOC_ARG); assert(false); } if (p == NULL) { std::cout << "no memory" << std::endl; exit(0); return false; } for (int i = 0; i < T::ALLOC_ARG; i++) { if (Head == NULL) { Head = &p[i]; Head->next = NULL; } else { p[i].next = Head; Head = &p[i]; } } return true; } template Alloc_Pool::Alloc_Pool() { Head = NULL; m_BaseIndex = 0; //InitializeCriticalSection(&m_cs); InternalAlloc(); } template Alloc_Pool::~Alloc_Pool() { for (int i = 0; i < m_BaseIndex; i++) free(PtrBase[i]); } template template T* Alloc_Pool::Alloc(X...Args) { std::lock_guard lg(lock); if (Head == NULL) { InternalAlloc(); } NODE* temp = Head; Head = Head->next; new(temp->t) T(Args...); return reinterpret_cast(temp->t); } template Alloc_Pool& Alloc_Pool::GetInstance() { static Alloc_Pool s; return s; } template void Alloc_Pool::Free(T* ptr) { ptr->~T(); int8_t* p = (int8_t*)ptr; p -= sizeof(NODE*); NODE* node = (NODE*)p; std::lock_guard lg(lock); node->next = Head; Head = node; }