tags:

views:

49

answers:

1

This is a followup from http://stackoverflow.com/questions/4062503/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.

+1  A: 

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
};
Roger Pate
Unfortunately the pool is used in groups of threads, not just a single one.
edA-qa mort-ora-y
@edA: Then the pool's methods should be thread-safe. If *each* map should use a different pool, make it a data member of the allocator which is not copied when the allocator is copied. This breaks some of the STL requirements, but you can use if it you're careful, or you'll have to use different container classes. (std::map isn't that hard to write.)
Roger Pate
This pool is then based on raw memory, not high level objects. That might gain me a bit, but I'm not sure. I'm hoping to avoid writing my own map, but as I look at the restrictions it may be unavoidable.
edA-qa mort-ora-y
@edA: Yes, the pool deals only with sized pieces of memory (just like malloc does), while the allocator deals with each type's details (construction, destruction).
Roger Pate
If there's something wrong with my answer, I'd like to know in addition to the downvote.
Roger Pate