3

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.

2

1 Answer 1

2

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
};
Sign up to request clarification or add additional context in comments.

5 Comments

Unfortunately the pool is used in groups of threads, not just a single one.
@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.)
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: 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).
If there's something wrong with my answer, I'd like to know in addition to the downvote.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.