edA-qa mort-ora-y
edA-qa mort-ora-y

Reputation: 31851

how to create an allocator for std::map using a pool of objects

This is a followup from stl allocator, copy constructor of other type, rebind

I am using std::map and want a custom allocator that can reuse the storage for the internal nodes. The items being stored are pointers, so I'm not talking about reusing them, just the internal allocations for the map.

The main requirements is that different instances of the map cannot share an object pool, it must be unique per instance.

I don't need a complete solution, I'd just like an idea of how to cope with the required copy constructor that takes allocators of a different type. I don't know how to manage the internal memory in that case.

Upvotes: 2

Views: 2035

Answers (1)

Roger Pate
Roger Pate

Reputation:

As you point out in the other question, the allocators shouldn't have any state. Use thread-local storage or a pointer in each allocator object to the memory pool: the allocators merely become a type-specific interface to that pool.

struct MemoryPool {
  // none of this depends on the type of objects being allocated
};

template<class T>
struct MyAllocator {
  template<class U> struct rebind { typedef MyAllocator<U> other; };

  MemoryPool *_pool;  // copied to any allocator constructed

  template<class U>
  MyAllocator(MyAllocator const &other) : _pool(other._pool) {}

  // allocate, deallocate use _pool
  // construct, destruct deal with T
};

Upvotes: 2

Related Questions