Placing new with std :: list

I am looking to implement a (double) linked list that only calls placement new internally, directing all the memory to a pool allocated with something like:

 char *memPool = new char[4096]; // One-off normal 'new' 

Initially, I was going to implement my own class, which takes a pointer to a pool of allocated resources (the class that controls a). However, first I want to be sure that I cannot achieve the same result with std::list . In particular, the third part of David Rodriguez's answer to this SO question bothers me.

It makes sense that std::list will have to call new and delete on its component nodes, but I want to change this behavior so that all nodes are distributed with placement new in my user pool. So my question is:

Is it possible to indicate that a placement new std::list , for example:

 std::list<std::shared_ptr<Cls>> myList = new (pool.getFreeAddr()) list<Cls>; 

should also allocate its nodes using a custom allocator so that everything is kept strictly inside my own memory pool?

(Note: I am aware of the need to use custom allocation / deletion functions using shared_ptrs if I also want them in a custom memory pool.)

+4
source share
1 answer

You must:

  • Write a MyAllocator class template that meets Allocator requirements ([allocator.requirements] in the standard).
  • Use std::list<T, MyAllocator<T> > instead of std::list<T> .

If you want the type of your list specifically std::list<T> (for example, because you want to call functions that take std::list<T> & and whose interface you cannot change), you are out of luck, the type of dispenser is part type of container.

Follow the requirements of the dispenser, they are strange. In particular, you'll need rebind for list , and it's a bit complicated.

In addition, in C ++ 03 there is no guarantee that allocator instances are respected, but only the type of allocator, which actually means that the pointer to the pool that you allocate should be stored with static duration, and not as an instance variable. I think this has been changed to C ++ 11, but I could be wrong. It really matters if you want to use several different pools in your program.

+5
source

All Articles