I looked at allocator classes but it seems STL containers must be able to use the default constructors to create the allocator
That's not true, all containers can be constructed with an allocator explicitly, so you can create your allocator object and then pass it to the container.
extern "C"
{
typedef void* (*allocation_function)(size_t);
typedef void (*deallocation_function)(void*);
}
template<typename T>
class Allocator
{
public:
typedef T value_type;
Allocator(allocation_function alloc, deallocation_function dealloc)
: m_allocate(alloc), m_deallocate(dealloc)
{ }
template<typename U>
Allocator(const Allocator<U>& a)
: m_allocate(a.m_allocate), m_deallocate(a.m_deallocate)
{ }
T* allocate(size_t n)
{ return static_cast<T*>(m_allocate(n * sizeof(T))); }
void deallocate(T* p, size_t)
{ m_deallocate(p); }
private:
template<typename U>
friend class Allocator<U>;
template<typename U>
friend bool operator==(const Allocator<U>&, const Allocator<U>&);
allocation_function m_allocate;
deallocation_function m_deallocate;
};
template<typename T>
bool operator==(const Allocator<T>& l, const Allocator<T>& r)
{ return l.m_allocate == r.m_allocate; }
template<typename T>
bool operator!=(const Allocator<T>& l, const Allocator<T>& r)
{ return !(l == r); }
Allocator<int> a(custom_malloc, custom_free);
std::vector<int, Allocator<int>> v(a);
If you're using not using C++11 yet then you need to provide a lot more members for your allocator to meet the old requirements, but the one above is OK for C++11. Using custom allocators in C++03 is difficult and not portable anyway, so you should aim to use a C++11 compiler if you need to do this.