问题由来,
考虑设计一个内存池类,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 };