Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class PoolAllocator: public std::allocator<std::pair<const KeyType, CodeType>> {
- class MemoryPool {
- public:
- std::stack<pointer, std::vector<pointer>> aa; // Available Addresses
- MemoryPool():
- bytes(new char[sizeof (CodeType) * globals::dms])
- {
- pointer begin = reinterpret_cast<pointer> (bytes.get());
- const pointer end = begin + globals::dms;
- while (begin != end)
- aa.push(begin++);
- }
- private:
- std::unique_ptr<char[]> bytes; // actual memory
- };
- public:
- pointer allocate(size_type n, std::allocator<void>::const_pointer = 0)
- {
- if (n > max_size())
- throw std::invalid_argument("MemoryPool::allocate(), bad `n'");
- // memory pool depleted
- if (mp.aa.empty())
- throw std::bad_alloc();
- pointer p = mp.aa.top();
- mp.aa.pop();
- return p;
- }
- /// @warning Naive implementation, assumes `p` is valid.
- void deallocate(pointer p, size_type n)
- {
- if (n > max_size())
- throw std::invalid_argument("MemoryPool::deallocate(), bad `n'");
- // memory pool full
- if (mp.aa.size() == globals::dms)
- throw std::runtime_error("MemoryPool::deallocate(), `aa' is full");
- mp.aa.push(p);
- }
- size_type max_size() const
- {
- return 1;
- }
- private:
- static MemoryPool mp;
- };
Advertisement