如何为动态分配的stl容器设置allocator?

时间:2016-09-16 22:14:41

标签: c++ c++11 memory-management tbb

我正在使用TBB自定义内存分配器。

tbb::memory_pool<std::allocator<char>> shortTermPool;
typedef tbb::memory_pool_allocator<Result*> custom_allocator;
std::vector<Result*,custom_allocator>* results =(std::vector<Result*,custom_allocator>*)shortTermPool.malloc(sizeof(std::vector<Result*,custom_allocator>));

问题是设置分配器是在构造函数中。 Malloc不会调用构造函数。默认用法是这样的:

tbb::memory_pool<std::allocator<char>> shortTermPool;
typedef tbb::memory_pool_allocator<Result*> custom_allocator;
std::vector<Result*,custom_allocator> results (custom_allocator(shortTermPool));

有没有办法做一个stl容器的malloc,然后再分配一个自定义分配器?

1 个答案:

答案 0 :(得分:6)

这样做之后:

std::vector<Result*,custom_allocator>* results = (std::vector<Result*,custom_allocator>*)shortTermPool.malloc(sizeof(std::vector<Result*,custom_allocator>));

您需要使用 placement-new 来构建对象:

new(results) std::vector<Result*,custom_allocator>(custom_allocator(shortTermPool));

虽然,下面这样的事情可能更具可读性:

using MemoryPool = tbb::memory_pool<std::allocator<char>>;
using CustomAllocator = tbb::memory_pool_allocator<Result*>;
using CustomVector = std::vector<Result*, CustomAllocator>;

MemoryPool shortTermPool;
void* allocatedMemory = shortTermPool.malloc(sizeof(CustomVector);
CustomVector* results = static_cast<CustomVector*>(allocatedMemory);
new(results) CustomVector(CustomAllocator(shortTemPool));

修改

请记住在指针上使用delete,因为它指向的内存未由new分配;并记得明确地破坏对象:

results->~CustomVector();

更完整:

MemoryPool shortTermPool;
void* allocatedMemory = shortTermPool.malloc(sizeof(CustomVector);
CustomVector* results = static_cast<CustomVector*>(allocatedMemory);
new(results) CustomVector(CustomAllocator(shortTemPool));

/* Knock yourself out with the objects */

/*NOTE: If an exception is thrown before the code below is executed, you'll have a leak! */

results->~CustomVector();
shorTermPool.free(results);

//Don't do
//delete results

您可能还希望探索使用带有自定义删除程序的智能指针来处理正确的破坏并释放从tbb的内存分配器获取的内存