我想知道有一个符合 C++ 标准库的 allocator
是否可行,它使用位于堆栈中的(固定大小的)缓冲区.
I was wondering if it practicable to have an C++ standard library compliant allocator
that uses a (fixed sized) buffer that lives on the stack.
不知何故,这个问题似乎还没有在 SO 上被这样问过,尽管它可能已经在别处隐含地回答了.
Somehow, it seems this question has not been ask this way yet on SO, although it may have been implicitly answered elsewhere.
所以基本上,就我的搜索而言,似乎应该可以创建一个使用固定大小缓冲区的分配器.现在,乍一看,这应该意味着它应该也可以有一个使用固定大小缓冲区的分配器,该缓冲区存在于"堆栈中,但它确实出现,周围没有广泛的此类实现.
So basically, it seems, as far as my searches go, that it should be possible to create an allocator that uses a fixed size buffer. Now, on first glance, this should mean that it should also be possible to have an allocator that uses a fixed size buffer that "lives" on the stack, but it does appear, that there is no widespread such implementation around.
让我举一个例子来说明我的意思:
Let me give an example of what I mean:
{ ...
char buf[512];
typedef ...hmm?... local_allocator; // should use buf
typedef std::basic_string<char, std::char_traits<char>, local_allocator> lstring;
lstring str; // string object of max. 512 char
}
这将如何实现?
另一个问题的答案(感谢 R. Martinho Fernandes) 链接到来自 Chromium 源的基于堆栈的分配器:http://src.chromium.org/viewvc/chrome/trunk/src/base/stack_container.h
The answer to this other question (thanks to R. Martinho Fernandes) links to a stack based allocator from the chromium sources: http://src.chromium.org/viewvc/chrome/trunk/src/base/stack_container.h
然而,这个类看起来非常奇特,特别是因为这个 StackAllocator
没有默认的构造函数——我在想每个分配器类都需要一个默认的ctor.
However, this class seems extremely peculiar, especially since this StackAllocator
does not have a default ctor -- and there I was thinking that every allocator class needs a default ctor.
显然,是一个符合标准的堆栈分配器 来自一个 Howard Hinnant.
它通过使用固定大小的缓冲区(通过引用的arena
对象)并在请求太多空间时回退到堆来工作.
It works by using a fixed size buffer (via a referenced arena
object) and falling back to the heap if too much space is requested.
这个分配器没有默认的构造函数,因为霍华德说:
This allocator doesn't have a default ctor, and since Howard says:
我已经用一个完全符合 C++11 的新分配器更新了这篇文章.
I've updated this article with a new allocator that is fully C++11 conforming.
我认为分配器不需要有默认构造函数.
I'd say that it is not a requirement for an allocator to have a default ctor.
这篇关于基于堆栈缓冲区的 STL 分配器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!