[Code] Template class for memory pool operation

xiaoxiao2021-03-05  24

// File name: Mempool.h // Author: moonwell // msn: Archonzhao@hotmail.com// Put #include "mempool.h" Before #include , "INITIALIZECRITICTIONANDSPINCOUNT function will appear" not defined "error #ifndef _MEM_POOL_H # define _MEM_POOL_H # define _WIN32_WINNT 0x0403 // For InitializeCriticalSectionAndSpinCount # ifdef _DEBUG # define _DEBUG_POOL # endif # include #include #include #ifdef _DEBUG_POOL # include #endif using namespace std; template class memPool {public: // init_count = mempool initially allocated number of objects (int init_count); ~ memPool (void); memtype * alloc (); // Read an element Void Free (MemType * Obj); // Delete an element private: vector m_free_node; // idle object list vector m_new_node; // Extra created object list #ifdef _debug_pool map m_map; // is used to detect whether the object is released in the middle of the #ENDIF MEMTYPE * m_HEAD; // Critical_Section m_sec;}; template Mempool :: Mempool (int init_count) {m_head = new memtype [init_count]; first put the memory of the Vector object to the original size, can improve the efficiency m_free_node.resize (Init_Count * 2) ; M_free_node.resize (0); // add the object to the free list for (int i = 0; i MemPool :: ~ Mempool (Void) {Vector ip; deletecriticalsection (& m_sec); delete [] m_head; // Delete all additional object For (it = m_new_node.begin) ); it! = m_new_node.end (); it) delete [] * it;} template metype * mempool :: alloc () {memtype * ptmp; EntercriticalSection; if (& m_sec); ! m_free_node.empty ()) {PTMP = * (- m_free_node.end ());

// Take the last object m_free_node.pop_back (); # ifdef _debug_pool m_map.ed (ptmp); # Endif} else {ptmp = new memory; // Create an additional object m_new_node.push_back (ptmp); // Add to additional list} LeaveCriticalSection (& m_sec); return ptmp;} template void memPool :: free (memtype * obj) {EnterCriticalSection (& m_sec); m_free_node.push_back (obj); # ifdef _DEBUG_POOL // obj has been Released? _Asserte (m_map.find (obj) == m_map.end ()); m_map [obj] = Obj; #ndif leavecriticalsection (& m_sec);} # Endif increases multiple free () detection on the original basis The function, which will cause an assertion to the same object twice.

转载请注明原文地址:https://www.9cbs.com/read-35948.html

New Post(0)