Code reference LEVELDB implementation of the memory pool method, because the actual work is temporarily unused to the memory pool, so here is just a simple memory pool implementation, the subsequent need, you can change the code according to actual requirements.
Arena.h
#ifndef ARENA_H#define ARENA_H#include <stdio.h> #include <vector> #include <stdint.h> #include <assert.h>//Memory pool class//destructor automatically frees memory class arena{public: arena (); ~arena (); //Memory Request function / /@bytes requested memory size //returns a pointer to memory char* Allocate (size_t bytes); //Memory usage function size_t memoryusage ( ) const { return memory_usage_ ; } size_t memoryremain () { return alloc_bytes_remaining_; }private: //Request memory function, use //when memory pool has less memory left than requested memory @bytes The size of the memory to be requested &NBSP;&NBSP;&NBSP;&NBsp;//returns a pointer to memory char* allocatefallback (size_t bytes); / /Application Block memory function, directly request a new block of memory //@block_bytes block memory size to be requested // Returns a pointer to memory char* allocatenewblock (size_t block_bytes); char* alloc_ptr_; //Pointer to memory size_t alloc_bytes_remaining_; //remaining available memory size std::vector<char*> blocks_; //Memory Pool size_t memory_usage_; //Total requested memory size arena (const arena&); void operator= (const Arena&);}; Inline char* arena::Allocate (size_t bytes) { assert (bytes > 0); if ( Bytes <= alloc_bytes_remaining_) { char* result = alloc_ptr_; alloc_ptr _ += bytes; alloc_bytes_remaining_ -= bytes ; return result; } return allocatefallback (bytes);} #endif // arena_h
Arena.cpp
#include "arena.h" #include <assert.h>//fixed block memory size static const int kblocksize = 4096; Arena::arena () : memory_usage_ (0) { alloc_ptr_ = null; alloc_bytes_remaining_ = 0;} Arena::~arena () { for (Size_t i = 0; i < blocks_.size (); i++) delete[] blocks_[i];} Char* arena::allocatefallback (size_t bytes) { if (bytes > KBLOCKSIZE/4) { char* result = allocatenewblock (bytes); return result; } alloc_ptr_ = allocatenewblock (kBlockSize); alloc_bytes_remaining_ = kblocksize; char* result = alloc_ptr_; alloc_ptr_ += bytes; alloc_bytes_ Remaining_ -= bytes; return result;} Char* arena::allocatenewblock (size_t block_bytes) { char* result = new char[block_bytes]; blocks_.push_back (Result); Memory_usage_ = memoryusage () + block_bytes + sizeof (char*); return result;}
C + + implements a memory pool