Gistrec

Memory Pool IMPL POC

Jun 17th, 2019
620
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. class PoolAllocator: public std::allocator<std::pair<const KeyType, CodeType>> {
  2.  
  3.     class MemoryPool {
  4.     public:
  5.  
  6.         std::stack<pointer, std::vector<pointer>> aa; // Available Addresses
  7.  
  8.         MemoryPool():
  9.             bytes(new char[sizeof (CodeType) * globals::dms])
  10.         {
  11.             pointer begin       = reinterpret_cast<pointer> (bytes.get());
  12.             const pointer end   = begin + globals::dms;
  13.  
  14.             while (begin != end)
  15.                 aa.push(begin++);
  16.         }
  17.  
  18.     private:
  19.  
  20.         std::unique_ptr<char[]> bytes; // actual memory
  21.     };
  22.  
  23. public:
  24.  
  25.     pointer allocate(size_type n, std::allocator<void>::const_pointer = 0)
  26.     {
  27.         if (n > max_size())
  28.             throw std::invalid_argument("MemoryPool::allocate(), bad `n'");
  29.  
  30.         // memory pool depleted
  31.         if (mp.aa.empty())
  32.             throw std::bad_alloc();
  33.  
  34.         pointer p = mp.aa.top();
  35.         mp.aa.pop();
  36.         return p;
  37.     }
  38.  
  39.     /// @warning Naive implementation, assumes `p` is valid.
  40.     void deallocate(pointer p, size_type n)
  41.     {
  42.         if (n > max_size())
  43.             throw std::invalid_argument("MemoryPool::deallocate(), bad `n'");
  44.  
  45.         // memory pool full
  46.         if (mp.aa.size() == globals::dms)
  47.             throw std::runtime_error("MemoryPool::deallocate(), `aa' is full");
  48.  
  49.         mp.aa.push(p);
  50.     }
  51.  
  52.     size_type max_size() const
  53.     {
  54.         return 1;
  55.     }
  56.  
  57. private:
  58.  
  59.     static MemoryPool mp;
  60. };
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment