• 转C++内存池实现


    #pragma once
    #ifndef _MEMORY_POOL_ 
    #define _MEMORY_POOL_
    #include <list>
    #include <Windows.h>
    using std::list;

    template <typename Type>
    class MemoryPool
    {
    private:
    int m_nMaxCount;
    int m_nFreeCount;
    list <Type*> m_pMemList;
    Type * m_pType;
    CRITICAL_SECTION m_csMemLock;
    public:
    MemoryPool(int nMax);
    ~MemoryPool();
    Type* New();
    void Delete(Type* p);
    int GetFreeCount();
    bool IsFull();
    };
    template <typename Type>
    MemoryPool<Type>::MemoryPool(int nMax)
    {
    m_pType=NULL;
    m_pType=new (std::nothrow) Type[nMax];
    if (m_pType!=NULL)
    {
    for (int i = 0; i < nMax; ++i)
    {
    m_pMemList.push_back(&m_pType[i]);
    }
    m_nMaxCount=nMax;
    m_nFreeCount=m_nMaxCount;
    }
    else
    {
    m_nMaxCount=0;
    m_nFreeCount=0;
    }
    InitializeCriticalSection(&m_csMemLock);
    }

    template <typename Type>
    inline MemoryPool <Type>::~MemoryPool()
    {
    delete[] m_pType;
    DeleteCriticalSection(&m_csMemLock);
    }

    template <typename Type>
    Type* MemoryPool <Type>::New()
    {

    Type* pNew=NULL;
    if (m_pType != NULL && m_nFreeCount > 0)
    {
    EnterCriticalSection(&m_csMemLock);
    pNew=m_pMemList.front();
    m_pMemList.pop_front();
    LeaveCriticalSection(&m_csMemLock);
    --m_nFreeCount;
    }
    return pNew;
    }

    template <typename Type>
    void MemoryPool <Type>::Delete(Type* p)
    {
    bool bIsValaidPointer = false;
    for (int i = 0;i < m_nMaxCount;++i)
    {
    if (&m_pType[i] == p)
    {
    //判断p是否是内存池中的内存指针,防止传入其他外部自己new的内存在内部释放
    bIsValaidPointer=true;
    }
    }
    list<Type*>::iterator iter;
    for (iter = m_pMemList.begin();iter != m_pMemList.end();++iter)
    {
    if (*iter==p)
    {
    //判断p是否已经被释放过了,防止对同一指针多次释放
    bIsValaidPointer = false;
    }
    }
    if (p != NULL && m_pType != NULL && m_nFreeCount < m_nMaxCount && bIsValaidPointer)
    {
    EnterCriticalSection(&m_csMemLock);
    m_pMemList.push_front(p);
    LeaveCriticalSection(&m_csMemLock);
    ++m_nFreeCount;
    }
    }
    template <typename Type>
    inline int MemoryPool<Type>::GetFreeCount() //获取剩余容量
    {
    return m_nFreeCount;
    }
    template <typename Type>
    inline bool MemoryPool <Type>::IsFull()
    {
    return m_nFreeCount == 0?true::false;
    }

    #endif

  • 相关阅读:
    九度oj 题目1051:数字阶梯求和
    九度oj 题目1472:求两个多项式的和
    九度oj 题目1173:查找
    九度oj 题目1447:最短路
    九度oj 题目1104:整除问题
    [Luogu] 维护序列
    [Luogu] 计算系数
    [Luogu] 聪明的质监员
    [Luogu] Mayan游戏
    [Luogu] 选择客栈
  • 原文地址:https://www.cnblogs.com/rosesmall/p/2491768.html
Copyright © 2020-2023  润新知