对象大小固定的单线程内存池设计
来源:互联网 发布:excel宏编程教程 编辑:程序博客网 时间:2024/06/05 18:17
类Rational通过重载new和delete以实现高效的内存分配,提高程序性能。
具体设计方案如下:
class Rational{public: Rational(int a = 0, int b = 1) :n(a), d(b) {} void* operator new(size_t size){ return memPool->alloc(size); } void operator delete(void* doomed, size_t size){ memPool->free(doomed); }private: int n; int d; static MemoryPool<Rational>* memPool;};/* 以下为内存分配与回收类## 标题 ##的实现*/template <class T>class MemoryPool{public: MemoryPool(size_t size = EXPANSION_SIZE); ~MemoryPool(); inline void* alloc(size_t size); inline void free(void* someElement);private: //空闲列表的下一个元素 MemoryPool<T>* next; //如果空闲列表为空,就按该大小扩展它 enum{ EXPANSION_SIZE = 32}; //添加空闲元素至空闲列表 void expandTheFreeList(inthowMany = EXPANSION_SIZE);};template <class T>MemoryPool<T>::MemoryPool(size_t size){ expandTheFreeList(size);}//析构函数 遍历空间列表,并删除所有元素template <class T>MemoryPool<T>::~MemoryPool(){ MemoryPool* nextPtr = next; for (nextPtr = next; nextPtr != NULL; nextPtr = next){ next = next->next; delete[] nextPtr; }}//分配内存template <class T>inlinevoid* MemoryPool<T>::alloc(size_t){ if (!next){//内存用尽则调用expandTheFreeList扩充 expandTheFreeList(); } MemoryPool<T>* head = next; next = head->next; return head;}//将内存回收到空闲列表template <class T>inlinevoid MemoryPool<T>::free(void* doomed){ MemoryPool<T>* head = static_cast<MemoryPool<T>*>(doomed); head->next = next; next = head;}//expandTheFreeList向堆中分配新元素,然后将它们连接到空闲列表中//当空闲列表被用尽时调用template <class T>void MemoryPool<T>::expandTheFreeList(int howMany){ //分配足够大的对象已包含下一个指针 size_t size = (sizeof(T) > sizeof(MemoryPool<T>*)) ? sizeof(T) : sizeof(MemoryPool<T>*); MemoryPool<T>* runner = static_cast<MemoryPool<T>*>(new char[size]); next = runner; for (int i = 0; i < howMany; i++){ runner->next = static_cast<MemoryPool<T>*>new char[size]; runner = runner->next; } runner->next = 0;}
读书笔记:《提高C++性能的编程技术》
0 0
- 对象大小固定的单线程内存池设计
- 单线程固定大小对象的内存池实现
- 单线程不固定大小对象的内存池实现
- 单线程环境中对象大小固定的内存池
- (2)单线程内存池--固定大小对象的内存池
- 单线程环境中对象大小可变的内存池
- 固定大小块的内存池设计
- (3)单线程内存池--可变大小的内存管理器
- 固定大小内存池设计与实现
- 固定大小的线程池(2)
- Java线程2-2 固定大小的线程池FixedThreadPool
- Java线程 - 固定大小线程池示例
- 固定单文档的窗口大小
- c++ 固定分配大小的简单内存池
- 简单实现一个固定大小的内存池
- C语言-固定大小内存池
- 单线程内存池
- 单线程内存池
- 括号配对&&合法性检测(php语言)
- KMP算法以及代码实现
- RT-thread-2.0.1移植(基于STM32F4xx)
- JAVA刚碰见的问题( java.lang.SecurityException: The jurisdiction policy files are not signed by a trusted s
- 苹果加急审核
- 对象大小固定的单线程内存池设计
- Gradle基础——Groovy语言
- RT-thread组件初始化代码分析
- java bean 代码生成器
- 【MyEclipse】——MyEclipse has detected that less than 5% of the 28M of PS Survivor Space...
- RT-thread main函数分析
- JavaScript - ajax请求的初步封装
- gitHub如何切换到非master分支的其他分支
- RT-thread finsh组件工作流程