问题由来,
考虑设计一个内存池类,http://www.ibm.com/developerworks/cn/linux/l-cn-ppp/index6.html?ca=drs-cn。
内存池类代码如下:
.h文件
1 #pragma once 2 3 4 #include <memory> 5 #include <iostream> 6 #include <windows.h> 7 using namespace std; 8 9 10 #define USHORT unsigned int 11 #define ULONG unsigned long 12 #define MEMPOOL_ALIGNMENT 4 13 14 #pragma warning( disable : 4291 ) 15 16 struct MemoryBlock 17 { 18 unsigned short nSize; 19 unsigned short nFree; 20 unsigned short nFirst; 21 //std::shared_ptr<MemoryBlock> pNext; 22 MemoryBlock* pNext; 23 char aData[1]; 24 25 static void* operator new(size_t, unsigned short nTypes, unsigned short nUnitSize) 26 { 27 return ::operator new(sizeof(MemoryBlock) + nTypes * nUnitSize); 28 } 29 30 static void operator delete(void *p, size_t) 31 { 32 ::operator delete (p); 33 } 34 35 MemoryBlock (unsigned short nTypes = 1, unsigned short nUnitSize = 0); 36 ~MemoryBlock() {} 37 38 }; 39 40 class MemoryPool 41 { 42 private: 43 //std::shared_ptr<MemoryBlock> pBlock; 44 MemoryBlock* pBlock; 45 unsigned short nUnitSize; 46 unsigned short nInitCount; 47 unsigned short nGrowSize; 48 CRITICAL_SECTION allocSection; 49 CRITICAL_SECTION freeSection; 50 51 public: 52 static unsigned char nMemoryIsDeleteFlag; //标记MemoryPool内存是否释放 53 54 public: 55 MemoryPool( unsigned short nUnitSize, 56 unsigned short nInitCount = 1024, 57 unsigned short nGrowSize = 256 ); 58 ~MemoryPool(); 59 60 void* Alloc(); 61 void Free( void* p ); 62 };
.cpp文件
1 #include "Memory.h" 2 3 4 MemoryBlock::MemoryBlock(unsigned short nTypes /* = 1 */, unsigned short nUnitSize /* = 0 */) 5 : nSize( nTypes * nUnitSize ) 6 , nFree( nTypes - 1 ) 7 , nFirst(1) 8 , pNext(NULL) 9 { 10 char * pData = aData; 11 for (unsigned short i = 1; i < nTypes; i++) 12 { 13 *reinterpret_cast<unsigned short*>(pData) = i; 14 pData += nUnitSize; 15 } 16 } 17 18 //不允许其他地方修改 19 unsigned char MemoryPool::nMemoryIsDeleteFlag = 0; 20 21 // UnitSize值不宜设置为过大值 22 MemoryPool::MemoryPool( unsigned short _nUnitSize, unsigned short _nInitCount , \ 23 unsigned short _nGrowSize ) 24 { 25 if ( _nUnitSize > 4 ) 26 nUnitSize = (_nUnitSize + (MEMPOOL_ALIGNMENT-1)) & ~(MEMPOOL_ALIGNMENT-1); 27 else if ( _nUnitSize <= 2 ) 28 nUnitSize = 2; 29 else 30 nUnitSize = 4; 31 32 nUnitSize = _nUnitSize; 33 nInitCount = _nInitCount; 34 nGrowSize = _nGrowSize; 35 pBlock = NU