1.模板类定义(使用了模板以适应不同对象的内存需求,内存池中的内存块则是以基于链表的结构进行组织)
<pre name="code" class="cpp">#include <QApplication>
#include <new>
#include <assert.h>
#include <QDebug>
template <class T, int BLOCK_NUM= 50>
class MemPool
{
public:
static void *operator new(size_t allocLen)
{
assert(sizeof(T) == allocLen);
qDebug()<<"allocLen = "<<allocLen;
if(!m_NewPointer)
MemAlloc();
unsigned char *rp = m_NewPointer;
m_NewPointer = *reinterpret_cast<unsigned char**>(rp); //由于头4个字节被“强行”解释为指向下一内存块的指针,这里m_NewPointer就指向了下一个内存块,以备下次分配使用。
return rp;
}
static void operator delete(void *dp)
{
*reinterpret_cast<unsigned char**>(dp) = m_NewPointer;
m_NewPointer = static_cast<unsigned char*>(dp);
qDebug()<<"memDelete";
}
private:
static void MemAlloc()
{
m_NewPointer = new unsigned char[sizeof(T) * BLOCK_NUM];
unsigned char **cur = reinterpret_cast<unsigned char**>(m_NewPointer); //强制转型为双指针,这将改变每个内存块头4个字节的含义。
unsigned char *next = m_NewPointer;
for(int i = 0; i < BLOCK_NUM-1; i++)
{
next += sizeof(T);
*cur = next;
cur = reinterpret_cast<unsigned char**>(next); //这样,所分配的每个内存块的头4个字节就被“强行“解释为指向下一个内存块的指针, 即形成了内存块的链表结构。
}
*cur = 0;
qDebug()<<"memAlloc";
}
static unsigned char *m_NewPointer;
protected:
~MemPool(){}
};
template<class T, int BLOCK_NUM >
unsigned char *MemPool<T, BLOCK_NUM >::m_NewPointer;
2.模板类的应用
class ExpMP : public MemPool<ExpMP>
{
char a[1024];
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ExpMP *aMP = new ExpMP();
delete aMP;
return a.exec();
}
运行结果为:
allocLen = 1024
memAlloc
memDelete
参考文献:百度百科之内存池篇。。。