Gistrec icon

Memory Pool IMPL POC

Gistrec | PRO | 06/17/19 11:40:07 AM UTC | 0 ⭐ | 638 👁️ | Never ⏰ | []
C++ |

1.47 KB

|

None

|

0 👍

/

0 👎

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;
};

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎