2016-09-16 6 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)); 

EDIT

メモリは、それが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 

ます。また、得適切な破壊やメモリの解放を処理するためにカスタムdeletersスマートポインタの使用を探求したいことがあり、明示的にこのようなオブジェクトを破壊することを忘れないでくださいtbbのメモリアロケータ

+0

このようにC++ 11の初期化されていないストレージをカスタムアロケータで使用できますか? – fish2000

関連する問題