杭州达内嵌入式培训火热招生中。。。|杭州达内c++培训火热招生中
您现在的位置: 杭州达内 >>C/C++>>C++培训技术内容:C++内存池的实现
C++培训技术内容:C++内存池的实现
杭州达内 - C/C++ 来源:未知 发布时间:2013-12-05 10:37

  达内C++培训小编为大家详解关于C++内存池的实现:
 /*  @file       MemoryPool.h
*   @note       HangZhou Hikvision System Technology Co., Ltd. All Right Reserved.
*   @brief      windows下内存池的实现
*   @author    
*   @date       11/15/2011
*   @note       V1.0  Created.
*   @warning Copyright (C) 2011 - All Rights Reserved
*/
#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
(本C++技术内容来自杭州达内培训技术论坛)


相关标签:C++培训(69)
 达内简介 达内就业 达内课程 联系我们 网站导航
杭州达内为上软件有限公司 Copyright @ 2007-2012 版权所有 苏ICP备10118953号-1
分享到: