对于几个小的std ::向量的连续内存分配? [英] Contiguous memory allocation for several small std::vectors?

查看:133
本文介绍了对于几个小的std ::向量的连续内存分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到一种方法来存储几个 std :: vectors ,每个不同的但已知的,相当小的大小,在连续的内存中。我意识到我可以写我自己的类,说一个非常大的数组,并指向数组的每个子部分的开始在更大的数组中被视为一个单独的实体,但似乎应该有一个更聪明的方式做这个。

I would like to find a way to store several std::vectors, each of a different but known and reasonably small size, in contiguous memory. I realize I could write my own class, say with a very large array and with pointers to the start of each subsection of the array within the larger array treated like a separate entity, but it seems like there should be a smarter way to do this.

是否有使用 allocators 的方法,例如创建连续的 std :: vectors ?我想不要重新发明轮子只是因为我想要这个记忆区域否则正常 std :: vectors

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

我不知道如何开始编码。我需要创建一个分配器,它接受指向内存的指针,在那里分配一个向量,然后以某种方式传回该向量的结束地址,所以下一个 std :: vector 的分配器可以抓住它,并再次做。 分配器如何返回值?

I don't know how to even begin coding. I need to create an allocator that takes a pointer to memory, allocates a vector there, and then somehow passes back the address of the end of that vector, so the next std::vector's allocator could grab that and do it again. How can an allocator return a value?

推荐答案

Howard Hinnant的 short_alloc 。我想在堆上分配,所以必须使用 new ,***但否则Howard的发布代码完全正确的我想要的。

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
...

我问的问题是 allocators 可以有构造函数,接受参数:

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);

我在另一个SO post中找到了代码引用:关于Hinnant的堆栈分配器的问题,它从CodeReview post中引用Chris Drew在他的评论中提出的。

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.

*** 代码确实使用 new 分配方法,留给我不确定这是分配在堆栈(如它从buf_ *的声明)或堆(使用 new )...

***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)...

这篇关于对于几个小的std ::向量的连续内存分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆