连续内存分配几个小的std ::载体? [英] Contiguous memory allocation for several small std::vectors?

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

问题描述

我想找到一种方法来存储数的std ::矢量,每一个不同的,但众所周知,合理体积小,在连续的内存。我知道我可以写我自己的类,具有非常大的数组和指针就像一个单独的实体处理较大的阵列中的阵列中的每个小节开始说了,但是看起来应该有这样做更聪明的方法

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.

有没有办法使用分配器的方式,例如,创造连续的std ::矢量?我想不是推倒重来,只是因为我想其他正常的std ::向量此内存局部性

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 ::矢量的分配器可以抓住这一点,做一遍。一个分配器如何返回一个值?

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?

推荐答案

解决方案是@ HowardHinnant的 short_alloc 。我想在堆上分配,以便必须使用,***否则霍华德张贴的code不正是我想要的。

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

从我的角度看缺少的部分,当我问的问题是,分配器可以有构造带参数:

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

我发现在另一个SO后的code参考:<一href=\"http://stackoverflow.com/questions/11648202/questions-about-hinnants-stack-allocator\">Questions哪些是从codeReview后克里斯德鲁建议在他的评论中上面引用Hinnant(欣南特)的堆栈分配。谢谢大家。

*** 的code确实使用分配法,留我不确定这是否是在栈上分配的(因为它似乎从buf_的声明*),或在堆(使用)...

***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天全站免登陆