Custom Pool Allocator Question

Discussion in 'C++' started by joe, May 8, 2007.

  1. joe

    joe Guest

    I have created a custom allocator for a multiset, and I am having a
    problem it seems because while the allocator has memory available to
    be used which is returned, the objects are never constructed on top of
    that memory. I expected my "construct" method to be called to handle
    this, but no one calls it.

    No more than MAX_OBJS object of class Obj will ever be allocated.

    #include<iostream>
    #include <set>

    const int MAX_OBJS = 100;
    template<typename T>
    class ObjAllocator
    {
    public:
    typedef T value_type;
    typedef value_type* pointer;
    typedef const value_type* const_pointer;
    typedef value_type& reference;
    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;

    template<typename U>
    struct rebind { typedef ObjAllocator<U> other; };

    explicit ObjAllocator() : m_available(0) { m_objs = new
    char[sizeof(Obj)*MAX_OBJS]; }

    ~ObjAllocator() {}

    explicit ObjAllocator(ObjAllocator const& rhs) {m_available =
    rhs.m_available;}

    template<typename U>
    ObjAllocator(ObjAllocator<U> const& rhs) { m_available =
    rhs.m_available;}

    pointer address(reference r) const {return &r;}
    const_pointer address(const_reference r) const { return &r;}

    pointer allocate(size_type cnt,
    typename std::allocator<void>::const_pointer
    hint = 0)
    {
    char *temp = &(m_objs[m_available * sizeof(Obj)]);
    m_available = (m_available+1) % MAX_OBJS;
    return reinterpret_cast<pointer>(temp);
    }

    void deallocate(pointer p, size_type) {}

    size_type max_size() const { return MAX_OBJS;}

    void construct(pointer p, const T& det) {std::cout<<"NEVER EVER
    CALLED"<<std::endl;}

    void destroy(pointer p){std::cout<<"ALSO NEVER CALLED"<<std::endl;}

    int m_available;
    char * m_objs;
    };

    class Thing
    {
    // Crashes on first "insert"
    std::multiset<Obj,ObjComparator,ObjAllocator<Obj> > m_multiSet;
    };

    Thanks!
     
    joe, May 8, 2007
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Brian Genisio
    Replies:
    12
    Views:
    8,084
    tom_usenet
    Jan 15, 2004
  2. Alex Vinokur
    Replies:
    16
    Views:
    12,334
    Alex Vinokur
    Aug 16, 2004
  3. joe
    Replies:
    3
    Views:
    420
    James Kanze
    May 24, 2007
  4. Juha Nieminen
    Replies:
    8
    Views:
    3,201
    Juha Nieminen
    Jul 11, 2008
  5. Rick Lawson
    Replies:
    8
    Views:
    825
    Graham Dumpleton
    Jul 17, 2009
Loading...

Share This Page