Custom Pool Allocator Question

J

joe

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!
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top