代码参考leveldb实现内存池的方法,由于实际工作中暂时未用到过内存池,因此这里只是一个简单的内存池实现,后续有需要时,可以根据实际需求再对代码进行修改。

arena.h

#ifndefARENA_H#defineARENA_H#include<stdio.h>#include<vector>#include<stdint.h>#include<assert.h>//内存池类//析构函数中自动释放内存classArena{public:Arena();~Arena();//内存申请函数//@bytes需要申请的内存大小//返回指向内存的指针char*Allocate(size_tbytes);//内存使用情况函数size_tMemoryUsage()const{returnmemory_usage_;}size_tMemoryRemain(){returnalloc_bytes_remaining_;}private://申请内存函数,当内存池中剩余内存少于申请内存时使用//@bytes需要申请的内存大小//返回指向内存的指针char*AllocateFallback(size_tbytes);//申请块内存函数,直接申请一块新的内存块//@block_bytes需要申请的块内存大小//返回指向内存的指针char*AllocateNewBlock(size_tblock_bytes);char*alloc_ptr_;//指向内存的指针size_talloc_bytes_remaining_;//剩余可用内存大小std::vector<char*>blocks_;//内存池size_tmemory_usage_;//总共申请的内存大小Arena(constArena&);voidoperator=(constArena&);};inlinechar*Arena::Allocate(size_tbytes){assert(bytes>0);if(bytes<=alloc_bytes_remaining_){char*result=alloc_ptr_;alloc_ptr_+=bytes;alloc_bytes_remaining_-=bytes;returnresult;}returnAllocateFallback(bytes);}#endif//ARENA_H


arena.cpp

#include"arena.h"#include<assert.h>//固定块内存大小staticconstintkBlockSize=4096;Arena::Arena():memory_usage_(0){alloc_ptr_=NULL;alloc_bytes_remaining_=0;}Arena::~Arena(){for(size_ti=0;i<blocks_.size();i++)delete[]blocks_[i];}char*Arena::AllocateFallback(size_tbytes){if(bytes>kBlockSize/4){char*result=AllocateNewBlock(bytes);returnresult;}alloc_ptr_=AllocateNewBlock(kBlockSize);alloc_bytes_remaining_=kBlockSize;char*result=alloc_ptr_;alloc_ptr_+=bytes;alloc_bytes_remaining_-=bytes;returnresult;}char*Arena::AllocateNewBlock(size_tblock_bytes){char*result=newchar[block_bytes];blocks_.push_back(result);memory_usage_=MemoryUsage()+block_bytes+sizeof(char*);returnresult;}