[代码]内存池操作的模板类
来源:互联网 发布:java spring mvc 实例 编辑:程序博客网 时间:2024/05/17 04:05
// 文件名 : Mempool.h
// 作者 : Moonwell
// Msn : archonzhao@hotmail.com
// 将#include "mempool.h"放在#include <windows.h>之前
// 否则会出现"InitializeCriticalSectionAndSpinCount函数没定义"的错误#ifndef _MEM_POOL_H
#define _MEM_POOL_H#define _WIN32_WINNT 0x0403 //For InitializeCriticalSectionAndSpinCount
#ifdef _DEBUG
#define _DEBUG_POOL
#endif#include <windows.h>
#include <crtdbg.h>
#include <vector>
#ifdef _DEBUG_POOL
#include <map>
#endifusing namespace std;
template<typename memtype>
class MemPool
{
public:
//init_count = 初始分配的对象个数
MemPool(int init_count);
~MemPool(void);memtype *alloc();// 读取一个元素
void free(memtype *obj);// 删除一个元素private:
vector<memtype *> m_free_node; //空闲的对象列表
vector<memtype *> m_new_node; //额外创建的对象列表
#ifdef _DEBUG_POOL
map<memtype *,memtype *> m_map;//用于检测对象是否被释放了多次
#endif
memtype *m_head;//初始创建时候的内存块的指针CRITICAL_SECTION m_sec;
};template<typename memtype>
MemPool<memtype>::MemPool(int init_count)
{
m_head = new memtype[init_count];//先把vector对象的内存增加到原来的两倍大小,可以提高效率
m_free_node.resize(init_count*2);
m_free_node.resize(0);//将对象添加到空闲列表
for(int i=0;i<init_count;i++)
m_free_node.push_back(&m_head[i]);InitializeCriticalSectionAndSpinCount(&m_sec,64);
}template<typename memtype>
MemPool<memtype>::~MemPool(void)
{
vector<memtype *>::iterator it;
DeleteCriticalSection(&m_sec);delete [] m_head;
// 删除所有额外创建的对象
for(it = m_new_node.begin();it != m_new_node.end();++it)
delete [] *it;}
template<typename memtype>
memtype *MemPool<memtype>::alloc()
{
memtype *ptmp;EnterCriticalSection(&m_sec);
if(!m_free_node.empty()) {
ptmp = *(--m_free_node.end()); //取最后一个对象
m_free_node.pop_back();
#ifdef _DEBUG_POOL
m_map.erase(ptmp);
#endif} else {
ptmp = new memtype; //创建额外的对象
m_new_node.push_back(ptmp); //添加到额外列表
}LeaveCriticalSection(&m_sec);
return ptmp;
}template<typename memtype>
void MemPool<memtype>::free(memtype *obj)
{
EnterCriticalSection(&m_sec);
m_free_node.push_back(obj);#ifdef _DEBUG_POOL //obj已经被释放了吗?
_ASSERTE(m_map.find(obj) == m_map.end());
m_map[obj] = obj;
#endif
LeaveCriticalSection(&m_sec);
}#endif
在原来基础上增加了多次free()检测的功能,对同一个对象释放两次将会引发一个断言.
- [代码]内存池操作的模板类
- Android中网络操作的模板代码
- 对GridView模板列内控件的操作代码
- 对GridView模板列内控件的操作代码
- 对GridView模板列内控件的操作代码
- Hibernate 操作数据库模板代码
- 循环队列代码(支持对共享内存的操作)
- java代码操作内存数据库
- C++模板类实现文件的操作
- myeclipse中类代码的注释模板
- 枚举类的模板代码-Java实现
- 代码模板的使用
- FlashBuilder的代码模板
- Android 的代码模板
- 代码的模板化
- Ibatis批量操作,代码模板如下:
- C++模板来实现一个通用的内存池.
- (转)C++ 实现内存自动托管的模板类
- appfuse1.7配置说明存在错误
- Excel 小工具:列出所有的sheet,然后点击其中的一个,自动跳过去
- 摘录一段《Mastoring Oracle SQL》——PL/SQL Calling Stored Functions from Queries
- 闲着无事,写了一个检测内存越界访问的工具(windows平台)
- SDL之四
- [代码]内存池操作的模板类
- 经典的句子(三)
- 使用API在VB中创建状态栏
- 什么是OFBiz?
- Windows CE初探 --(转载焦点安全文章:http://www.xfocus.net/articles/200411/747.html)
- C++ Primer
- IReport与JasperReport开发详解一
- XWindow使用及感受
- 占个位置,test