开发者

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,开发者_Python百科 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.


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
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜