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

How to set allocator for dynamically allocated stl container?

我正在使用 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,然后分配自定义分配器?

完成后:

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 的内存分配器

获得的内存的适当销毁和释放