2016-09-16 91 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