C++ 实现一个简易的内存池

下面是一个简单的内存池思想的版本,实现的思想如下:

  1. 通过维护一个freeNodeHeader链表。当要申请空间的时候,就从链表上面摘下一个结点;要释放一个空间的时候,就从将释放的结点重新插入到链表里面。

  2. 每个结点的大小是提前通过template传入的,就是要分配的对象的大小。

Q1 : 为什么要写一个内存池,默认的malloc不挺好的吗?
A1 :new 和 delete 是一个成本比较高的操作,因为需要到堆上开辟和释放空间。如果可以提前开辟好一大块空间,然后,下次使用的时候,就不需要可以直接使用内存池里面的空间,而不是去调用new和delete。这样可以会更加高效。(使用线程池的目的也是这样的)

Q2 : 自己设计的内存池会比malloc好吗?会不会是负优化?
A2 : 这个问题,我也在思考。下面是我的思考(不一定是正确的答案)

  1. 自己设计内存池一定是基于一个特定的一个场景,如果在这个特定的场景下面,一个针对这个场景下设计出来的内存池也许会比默认的更好,但是如果这个场景是一个通用的场景,那我觉得默认的也许是更好的。
    就像使用STL一样,如果知道了里面存放的元素是int,然后知道了元素数量,知道了对元素常用的操作。那么完全可以设计出一个比STL更高效的函数。但是如果这是一个通用的,可以大范围被使用的场景,那么可能STL是平均下来最好的结果。

  2. 作为一个初学者,了解内存池的工作原理,可以更好的理解一门编程语言的内存分配机制。这对深入的学习非常有必要。我觉得还是应该学习学习的。哪怕你写的内存池是一个垃圾。

#include <iostream>
using namespace std;

template<int ObjectSize, int NumofObjects = 20>   
class MemPool {
private:
    struct FreeNode {
        FreeNode* pNext;
        char data[ObjectSize];
    };

    FreeNode * freeNodeHeader;     //表示空闲链表
public:
    MemPool() {
        //init freeNodeHeader
        this->freeNodeHeader = new FreeNode[NumofObjects];
        for (int i = 0; i < NumofObjects - 1; i++) {
            freeNodeHeader[i].pNext = &freeNodeHeader[i + 1];
        }
        freeNodeHeader[NumofObjects-1].pNext = NULL;

    }

    ~MemPool() {
        cout << " ~ 析构函数 " << endl;
        delete[] freeNodeHeader;
    }

    //函数的实现在下面
    void* malloc() {
        if (freeNodeHeader==NULL) {  //空间没有了
            //分配一段新的空间
            cout << "重新添加了空间" << endl;
            FreeNode * newfreeNodeHeader = new FreeNode[NumofObjects];
            for (int i = 0; i < NumofObjects - 1; i++) {
                newfreeNodeHeader[i].pNext = &newfreeNodeHeader[i + 1];
            }
            newfreeNodeHeader[NumofObjects-1].pNext = NULL;   
            
            //于是又有了空间
            freeNodeHeader = newfreeNodeHeader;
        }
        cout << "分配一个空间" << endl;
        FreeNode * ret = freeNodeHeader;
        freeNodeHeader = freeNodeHeader->pNext;
        ret->pNext = NULL;
        return ret;
    }

    void free(void* p) {
        cout << "释放一个空间" << endl;
        FreeNode* pNode = (FreeNode*)p;
        pNode->pNext = freeNodeHeader;//将释放的节点插入空闲节点头部
        freeNodeHeader = pNode;
    }
};

//一个实例类,用来作为测试
class ActualClass {
    static int count;
    int No;

public:
    ActualClass() {
        No = count;
        count++;
    }

    void print() {
        cout << this << ": ";
        cout << "the " << No << " object" << endl;
    }

    void* operator new(size_t size);
    void operator delete(void* p);


    void* operator new[](size_t size);
    void operator delete[](void *p,size_t size);
};

MemPool<4, 5> mp;

void* ActualClass::operator new(size_t size) {
    cout << "size " << size << endl;
    return mp.malloc();
}

void ActualClass::operator delete(void* p) {
    mp.free(p);
}

void* ActualClass::operator new[](size_t size) {
    cout << "size " << size << endl;
    cout << "自定义的内存池并不支持申请多个空间,所以调用默认的malloc" << endl;
    return malloc(size);
}

void ActualClass::operator delete[](void *p , size_t size)
{
    cout << "调用默认的free" << endl;
    cout<<"delete [] size : "<<size<<endl;
    free(p);
}

int ActualClass::count = 0;



int main()
{
    for (int i = 0; i < 3; i++) {
        ActualClass* p = new ActualClass;
        p->print();
    }

    ActualClass* p1 = NULL;
    p1 = new ActualClass;
    p1->print();

    ActualClass* p2 = new ActualClass;
    p2->print();

    delete(p1);

    ActualClass* p3 = new ActualClass;
    p3->print();

    //to-do
    //目前内存池只能分配固定大小的空间,
        //对于new[5] , 他申请内存的大小是 5*sizeof(ActualClass) + 4 
        // 但是实现的内存池只能分配固定大小,于是就使用malloc分配了
        ActualClass* p4 = new ActualClass[5];
    delete [] p4;
        //ActualClass* p5 = new ActualClass[5];
    //ActualClass* p6 = new ActualClass[5];

    system("pause");
    return 0;
};

分享另外一个版本:

基本的实现是和上面的一个相同的:


#include <iostream>
#include <windows.h>

using namespace std;

#include "MemoryPool.h"
#include "MTMemoryPool.h"

class CTest
{
public:
    int m_n;
    int m_n1;

    void* operator new(size_t size)
    {
        void* p = s_pool->Alloc(size);
        return p;
    }

    void operator delete(void* p, size_t size)
    {
        s_pool->Free(p);
    }

    static void NewPool()
    {
        s_pool = new CMemoryPool<CTest>;
        //s_pool = new CMTMemoryPool<CMemoryPool<CTest>, CCriticalSection>;
    }

    static void DeletePool()
    {
        delete s_pool;
        s_pool = NULL;
    }

    static CMemoryPool<CTest>* s_pool;
    //static CMTMemoryPool<CMemoryPool<CTest>, CCriticalSection>* s_pool;
};

CMemoryPool<CTest>* CTest::s_pool = NULL;
//CMTMemoryPool<CMemoryPool<CTest>, CCriticalSection>* CTest::s_pool = NULL;

void testFun()
{
    int i;
    const int nLoop = 10;
    const int nCount = 10000;

    for (int j = 0; j<nLoop; ++j)
    {
        typedef CTest* LPTest;
        LPTest arData[nCount];
        for (i = 0; i <nCount; ++i)
        {
            arData[i] = new CTest;
        }

        for (i = 0; i <nCount; ++i)
        {
            delete arData[i];
        }
    }
}

int main(int argc, char* argv[])
{
    {
        unsigned int dwStartTickCount = GetTickCount();

        CTest::NewPool();

        testFun();

        CTest::DeletePool();

        cout << "total cost" << GetTickCount() - dwStartTickCount << endl;
    }


    system("pause");

    return 0;
    
}

//http://www.cppblog.com/weiym/archive/2012/05/05/173785.html

Memory.h

template<typename T>   //这里的T指的是 : CTest类
class CMemoryPool
{
private:
    CMemoryPool<T>* m_pFreeList;

public:
    enum { EXPANSION_SIZE = 32 };

    CMemoryPool(unsigned int nItemCount = EXPANSION_SIZE)
    {
        ExpandFreeList(nItemCount);
    }

    ~CMemoryPool()
    {
        //free all memory in the list
        CMemoryPool<T>* pNext = NULL;
        for (pNext = m_pFreeList; pNext != NULL; pNext = m_pFreeList)
        {
            m_pFreeList = m_pFreeList->m_pFreeList;
            delete[](char*)pNext;
        }
    }

    void* Alloc(unsigned int /*size*/)
    {
        if (m_pFreeList == NULL)
        {
            ExpandFreeList();
        }

        //get free memory from head
        CMemoryPool<T>* pHead = m_pFreeList;
        m_pFreeList = m_pFreeList->m_pFreeList;
        return pHead;
    }

    void Free(void* p)
    {
        //push the free memory back to list
        CMemoryPool<T>* pHead = static_cast<CMemoryPool<T>*>(p);
        pHead->m_pFreeList = m_pFreeList;
        m_pFreeList = pHead;
    }

protected:
    //allocate memory and push to the list
    void ExpandFreeList(unsigned nItemCount = EXPANSION_SIZE)
    {
        unsigned int nSize = sizeof(T) > sizeof(CMemoryPool<T>*) ? sizeof(T) : sizeof(CMemoryPool<T>*);     //取大的

        //申请一段空间
        CMemoryPool<T>* pLastItem = static_cast<CMemoryPool<T>*>(static_cast<void*>(new char[nSize]));
        m_pFreeList = pLastItem;

        for (int i = 0; i<nItemCount - 1; ++i)
        {
            pLastItem->m_pFreeList = static_cast<CMemoryPool<T>*>(static_cast<void*>(new char[nSize]));
            pLastItem = pLastItem->m_pFreeList;
        }

        pLastItem->m_pFreeList = NULL;
    }
};

MTMemoryPool.h (加锁的版本)

#pragma once
class CCriticalSection
{
public:
    CCriticalSection()
    {
        InitializeCriticalSection(&m_cs);
    }

    ~CCriticalSection()
    {
        DeleteCriticalSection(&m_cs);
    }

    void Lock()
    {
        EnterCriticalSection(&m_cs);
    }

    void Unlock()
    {
        LeaveCriticalSection(&m_cs);
    }

protected:
    CRITICAL_SECTION m_cs;
};

template<typename POOLTYPE, typename LOCKTYPE>
class CMTMemoryPool
{
public:
    void* Alloc(unsigned int size)
    {
        void* p = NULL;
        m_lock.Lock();
        p = m_pool.Alloc(size);
        m_lock.Unlock();

        return p;
    }

    void Free(void* p)
    {
        m_lock.Lock();
        m_pool.Free(p);
        m_lock.Unlock();
    }

private:
    POOLTYPE m_pool;
    LOCKTYPE m_lock;
};

read more :
深入探究C++的new/delete操作符:
https://kelvinh.github.io/blog/2014/04/19/research-on-operator-new-and-delete/

C++ 实现高性能内存池 :
https://blog.csdn.net/xjtuse2014/article/details/52302083

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。