简单的内存池分析

来源:互联网 发布:linux 复制覆盖文件 编辑:程序博客网 时间:2024/06/10 19:29
//代码引用了百度百科
typedef unsigned char UCHAR;template<class T,int BLOCK_NUM=50>class GenericMP{public: static VOID* operator new(size_t allocLen) {  if (!m_NewPointer)   MyAlloc();  UCHAR* rp = m_NewPointer;  m_NewPointer = *reinterpret_cast<UCHAR**>(rp);  return rp; } static VOID operator delete(VOID* dp) {  *reinterpret_cast<UCHAR**>(dp) = m_NewPointer;  m_NewPointer = static_cast<UCHAR*>(dp); }private: static VOID MyAlloc() {  m_NewPointer = new UCHAR[sizeof(T)*BLOCK_NUM];  UCHAR** cur = reinterpret_cast<UCHAR**>(m_NewPointer);  UCHAR* next = m_NewPointer;  for (int i = 0; i < BLOCK_NUM-1; i++)  {   next += sizeof(T);   *cur = next;   cur = reinterpret_cast<UCHAR**>(next);  }  *cur = 0; } static UCHAR* m_NewPointer;protected: ~GenericMP(){}};template<class T,int BLOCK_NUM>UCHAR* GenericMP<T,BLOCK_NUM>::m_NewPointer;class ExpMP : public GenericMP<ExpMP>{ UCHAR a[1024];};int _tmain(int argc, _TCHAR* argv[]){ ExpMP* aMP = new ExpMP;  delete aMP; system("pause"); return 0;}


其中new的时候调用了私有的MyAlloc()函数,该函数分配预先设好大小的内存,然后通过类型转换

  1. synamic_cast一般用在父类和子类指针或应用的互相转化;   
  2. static_cast一般是普通数据类型(如int m=static_cast<int>(3.14));   
  3. reinterpret_cast很像c的一般类型转换操作   
  4. const_cast是把cosnt或volatile属性去掉 

第三种对指针转成指针的指针,也就是前4个字节,用这前4个字节存储下一块内存的首地址,结构类似于链表,而重载的new操作符只在第一次分配内存,随后都是直接分配事先分配好的地址。删除内存的时候也是把该内存加回去,类似链表操作。

原创粉丝点击