将STL分配器与STL向量一起使用 [英] Using STL Allocator with STL Vectors

查看:70
本文介绍了将STL分配器与STL向量一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是基本问题.有一个我依赖的API,它的方法使用以下语法:

Here's the basic problem. There's an API which I depend on, with a method using the following syntax:

void foo_api (std::vector<type>& ref_to_my_populated_vector);

有问题的代码区域需要大量的性能,因此我想避免使用堆来分配内存.结果,我创建了一个自定义分配器,该分配器在堆栈上分配矢量所需的内存.因此,我现在可以将向量定义为:

The area of code in question is rather performance intensive, and I want to avoid using the heap to allocate memory. As a result, I created a custom allocator which allocates the memory required for the vector on the stack. So, I can now define a vector as:

// Create the stack allocator, with room for 100 elements
my_stack_allocator<type, 100> my_allocator;

// Create the vector, specifying our stack allocator to use
std::vector<type, my_stack_allocator> my_vec(my_allocator);

这很好.与标准向量相比,使用堆栈分配向量进行性能测试表明性能大约快4倍.问题是,我不能打电话给foo_api!所以...

This is all fine. Performance tests using the stack allocated vector compared to the standard vector show performance is roughly 4x faster. The problem is, I can't call foo_api! So...

foo_api(my_vec); // Results in an error due to incompatible types.
// Can't convert std::vector<type> to std::vector<type, allocator>

有解决方案吗?

推荐答案

您必须像函数期望的那样使用默认分配器.您有两种不同的类型,没有办法解决.

You have to use the default allocator just as the function expects. You have two different types, and there's no way around that.

在对向量进行操作之前只需调用reserve即可获得内存分配.

Just call reserve prior to operating on the vector to get the memory allocations out of the way.

考虑可能发生的坏事.该函数可能会占用您的向量,并开始添加更多元素.很快,您可能会溢出分配的堆栈空间.哎呀!

Think about the bad things that could happen. That function may take your vector and start adding more elements. Soon, you could over-flow the stack space you've allocated; oops!

如果您真的很担心性能,那么更好的方法是用自定义内存管理器替换operator new和kin.我这样做了,分配可以大大改善.对我来说,分配大小为512或更小的大小大约需要4次操作(移动几个指针);我用了一个池分配器)

If you're really concerned about performance, a much better route is to replace operator new and kin with a custom memory manager. I have done so and allocations can be hugely improved. For me, allocating sizes of size 512 or less is about 4 operations (move a couple pointers around); I used a pool allocator)

这篇关于将STL分配器与STL向量一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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