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

use*_*882 3 c++ memory-management tbb c++11

我正在使用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>));
Run Code Online (Sandbox Code Playgroud)

问题是设置分配器是在构造函数中.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));
Run Code Online (Sandbox Code Playgroud)

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

Whi*_*TiM 6

这样做之后:

std::vector<Result*,custom_allocator>* results = (std::vector<Result*,custom_allocator>*)shortTermPool.malloc(sizeof(std::vector<Result*,custom_allocator>));
Run Code Online (Sandbox Code Playgroud)

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

new(results) std::vector<Result*,custom_allocator>(custom_allocator(shortTermPool));
Run Code Online (Sandbox Code Playgroud)

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

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));
Run Code Online (Sandbox Code Playgroud)

编辑

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

results->~CustomVector();
Run Code Online (Sandbox Code Playgroud)

更完整:

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
Run Code Online (Sandbox Code Playgroud)

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