Continuous memory allocation for a few small std :: vectors?

I would like to find a way to store several std::vectors , each of which is different, but well-known and quite small in adjacent memory. I understand that I can write my own class, say, with a very large array and with pointers to the beginning of each subsection of the array in a larger array, treated as a separate object, but there seems to be a smarter way to do this.

Is there a way to use allocators , for example, to create contiguous std::vectors ? I would not want to reinvent the wheel just because I want this memory locality to be otherwise normal std::vectors

I do not know how to start coding. I need to create a allocator that takes a pointer to memory, allocates a vector there and then somehow returns the address of the end of this vector, so the next std::vector allocator could grab this and do it again. How to return allocator value?

+8
c ++ arrays vector allocator
source share
2 answers

The solution is @HowardHinnant short_alloc . I want to allocate a bunch, so I need to use new , ***, but otherwise the published Howard code does exactly what I want.

 template <std::size_t N> class arena {... char* buf_ = new char[N] // still need to align this but not sure of the syntax // to do that with a new statement ... 

The missing piece from my point of view, when I asked the question, was that allocators could have constructors that takes arguments:

 constexpr int N = 1000*sizeof(int); arena<N> myArena; std::vector<int, short_alloc<int, N>> x(MyArena); 

I found the code link in another SO post: Questions about the Hinnant stack distributor , which is referenced by the CodeReview comment suggested by Chris Drew in his comment above. Thanks to everyone.

*** The code uses new in the allocate method, leaving me unsure whether this is allocated on the stack (as seen from the buf_ * declaration) or on the heap (using new ) ...

+1
source share

For your requirement, I would use a custom allocator that extends std :: allocator and overrides allocate, a deallocate method that grabs chunks from a memory pool. If you already know the required maximum size, choosing the size of the memory pool should not be a problem.

0
source share

All Articles