Contiguous memory allocation for several small std::vectors?

房东的猫 提交于 2019-12-05 03:22:22
sunny

The solution is @HowardHinnant's short_alloc. I want to allocate on the heap so have to use new,*** but otherwise Howard's posted 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 perspective when I asked the question was that allocators can have constructors that take arguments:

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

I found the code reference in another SO post: Questions about Hinnant's stack allocator which was referenced from the CodeReview post Chris Drew suggested in his comment above. Thank you all.

***The code does use new in the allocate method, leaving me unsure of whether this is allocated on the stack (as it appears from the declaration of buf_*) or on the heap (use of new)...

For your requirement, I would implement custom allocator that extends std::allocator and overrides allocate, deallocate method that grabs chunks from a memory pool. If you already know the maximum size required, selecting memory pool size shouldn't be a problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!