2016-09-16 93 views
2

我正在使用TBB自定义内存分配器。如何为动态分配的stl容器设置分配器?

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,再后来分配一个自定义分配器?

回答

5

这样做后:

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

您将需要使用投放新构造对象:

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)); 

编辑

记住就因为它指向的不是由new分配的内存指针使用delete;记得要明确地破坏这样的目标:更彻底

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 */ 

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

//Don't do 
//delete results 

您可能还需要探索与定制删除器使用智能指针来处理适当的破坏和内存释放得到从tbb的内存分配器

+0

能以这种方式使用C++ 11未初始化的存储与自定义分配器吗? – fish2000