Advertisement
Guest User

AllocatorTwoInOne

a guest
Apr 23rd, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | None | 0 0
  1. #include <vector>
  2. #include <stack>
  3.  
  4. class FixedAllocator {
  5.  public:
  6.   FixedAllocator(size_t chunk_size, size_t page_size);
  7.   void *Allocate();
  8.   void Deallocate(void *value);
  9.  
  10.  private:
  11.   size_t chunk_size;
  12.   size_t page_size;
  13.   std::vector<std::vector<unsigned char>> pool;
  14.   std::stack<unsigned char*> free_memory;
  15. };
  16.  
  17. FixedAllocator::FixedAllocator(size_t chunk_size, size_t page_size) {
  18.   this->chunk_size = chunk_size;
  19.   this->page_size = page_size;
  20. }
  21.  
  22. void *FixedAllocator::Allocate() {
  23.   if (free_memory.empty()) {
  24.     pool.emplace_back(page_size * chunk_size);
  25.     for (size_t i = 0; i < page_size * chunk_size; i += chunk_size)
  26.       free_memory.push(&pool.back()[i]);
  27.   }
  28.   auto top_memory = free_memory.top();
  29.   free_memory.pop();
  30.   return top_memory;
  31. }
  32.  
  33. void FixedAllocator::Deallocate(void *value) {
  34.   auto del_memory = static_cast<unsigned char *>(value);
  35.   free_memory.push(del_memory);
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement