通过将boost :: pool_allocator作为参数

时间:2017-02-03 22:35:56

标签: c++ boost allocator

我有一段代码将在循环中运行并在每次迭代时创建std::vector,因此我希望使用Boost的pool_allocator来提高效率。但是,我使用的库不允许我将分配器作为模板参数传递:

  std::vector<int, boost::pool_allocator<int> > v;

  // This doesn't work because the library doesn't support the new type with the custom allocator
  library::processVector(v);

所以我想把分配器作为一个参数传递来解决它:

auto pool{boost::pool_allocator<int>()};
std::vector<int> v(pool);

但是这给了我一个编译错误:

error: no matching function for call to ‘std::vector<int>::vector(int, boost::pool_allocator<int>&)’

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

我担心你不能这样做。用于标准容器的分配器必须作为模板参数传递。如果确实提供了不同的分配器类型作为模板参数,则传递给容器构造函数的allocator参数的类型必须完全匹配或可以隐式转换为allocator模板参数,因此它应该是:

 typedef boost::pool_allocator<int> pool;
 std::vector<int, pool> v(pool);

答案 1 :(得分:0)

你真的需要在每次迭代时创建一个向量吗?

通常,您在循环外创建向量,并在每次迭代时创建.clear()。这样就可以重用已经分配的内存。

当然,这在任何情况下都无济于事。例如,如果该库通过std::move().swap()将其分配给另一个库而从向量移出,则无法提供帮助。