具有堆栈和动态分配的容器 [英] container with stack and dynamic allocation

查看:112
本文介绍了具有堆栈和动态分配的容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个容器,该容器使用少量元素的本地缓冲区,并且仅在元素数量超过特定限制时才使用堆分配?与大多数std::string实现类似.

Is there a container that uses a local buffer for a small number of elements, and uses a heap allocation only when the number of elements exceeds a certain limit? Similar to what most std::string implementations do.

背景

在以下(简化的)上下文中使用该容器:

The container is used in the following (simplified) context:

Foo foo;                     // some data
vector<HandlerPtr> tagged;   // receives "tagged" items

// first pass: over all items in someList
for each(HandlerPtr h in someList)
{
  h->HandleFoo(foo);         // foo may become tagged or untagged here
  if (foo.Tagged())
    tagged.push_back(h);
}
for(auto itr=tagged.rbegin(); itr!=tagged.end(); ++itr)
{
  // ...
}

此代码部分的调用频率很高,但标记项很少见,someContainer中的项数通常很少,但没有限制.我不能轻易使用预分配的更全局"缓冲区.目的是避免频繁分配.

This code part has high call frequency, but tagging an item is rather rare, number of items in someContainer is usually low but unbound. I can't use a preallocated "more global" buffer easily. The goal is to avoid the frequent allocation.

通话频率

  • 常见:没有项目被标记. std :: vector很好
  • 常见:只有少数几个项之一被标记.导致我想要避免的高频分配
  • 非常罕见,但必须得到支持:someList在首次通过时会增长,无法预测但仍然很低的项目数

推荐答案

没有标准的容器可以保证这种行为.但是,如果您愿意的话,可以创建一个自定义的STL兼容分配器类,该类从小的堆栈缓冲区中提取以进行小的分配,并且仅在请求的分配大小超过堆栈缓冲区的大小时才执行堆分配.您可以将自定义分配器类作为std::vector<T, Alloc>的第二个模板参数插​​入.

There is no standard container which guarantees this sort of behavior. However, if you're up to it, you can create a custom STL-compatible allocator class that draws from a small stack buffer for small allocations, and only performs a heap allocation when the requested allocation size exceeds the size of the stack buffer. You can plug-in your custom allocator class as the second template parameter for std::vector<T, Alloc>.

有关创建自定义分配器的信息,您应该阅读此文章.

For information on creating a custom allocator, you should read this article.

这篇关于具有堆栈和动态分配的容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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