/** * @file WMemoryFactory.h * @brief 通用内存池 * @author 沙漠乌鸦 * @time 2009-12-25 */ #pragma once #include #include #include namespace wuya { #define WMF_MEMORYSIZE 2048 /** @brief 单个内存管理器 */ template class AFX_EXT_CLASS WMemory { public: WMemory(void) : m_stCount(0) , m_stPos(-1) { } ~WMemory(void) { } T* New() { if(m_stCount == WMF_MEMORYSIZE) return NULL; // 从废弃内存中申请 size_t stCount = m_listpDisuse.size(); if(stCount > 0) { ++m_stCount; T* pObj = m_listpDisuse.back(); m_listpDisuse.pop_back(); return pObj; } // 从有有效游标中获取 ++m_stCount; ++m_stPos; return m_arrayMemory + m_stPos; } BOOL Delete(T* pVal) { if(m_stCount == 0) return FALSE; if(pVal >= m_arrayMemory && pVal < (m_arrayMemory + WMF_MEMORYSIZE)) { int iIndex = (int)(pVal-m_arrayMemory); m_arrayMemory[iIndex] = T(); --m_stCount; m_listpDisuse.push_back(pVal); return TRUE; } return FALSE; } private: T m_arrayMemory[WMF_MEMORYSIZE]; ///< 内存 size_t m_stCount; ///< 使用个数 size_t m_stPos; ///< 游标 std::list m_listpDisuse; ///< 保存废弃的指针 }; /** @brief 内存池 */ template class AFX_EXT_CLASS WMemoryFactory { public: ~WMemoryFactory(void) { Clear(); } // 获取唯一指针 static WMemoryFactory* GetInstance() { if(m_InstancePtr.get() == NULL) { m_InstancePtr.reset(new WMemoryFactory()); } return m_InstancePtr.get(); } // 动态分配指针 T* CreateObject() { std::vector*>::iterator itr = m_vecpMemory.begin(); for(; itr != m_vecpMemory.end(); ++itr) { T* pObject = (*itr)->New(); if(pObject != NULL) return pObject; } WMemory* pObjectMemory = new WMemory; m_vecpMemory.push_back(pObjectMemory); return pObjectMemory->New(); } // 删除指针 void DeleteObject(T* pObject) { std::vector*>::iterator itr = m_vecpMemory.begin(); for(; itr != m_vecpMemory.end(); ++itr) { WMemory* pMemory = (*itr); if(pMemory != NULL && pMemory->Delete(pObject)) break; } } // 清空内存 void Clear() { std::vector*>::iterator itr = m_vecpMemory.begin(); for(; itr != m_vecpMemory.end(); ++itr) { delete *itr; } m_vecpMemory.clear(); } protected: WMemoryFactory(void) { } WMemoryFactory(const WMemoryFactory&); WMemoryFactory& operator = (const WMemoryFactory&); private: std::vector*> m_vecpMemory; static std::auto_ptr m_InstancePtr; ///< 唯一实例 }; template std::auto_ptr> WMemoryFactory::m_InstancePtr; /** @brief 内存池删除器 */ template struct AFX_EXT_CLASS WMemoryDelete { void operator()(T* pObj) { WMemoryFactory::GetInstance()->DeleteObject(pObj); } }; };