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

이 일 후 :

new(results) std::vector<Result*,custom_allocator>(custom_allocator(shortTermPool)); 

비록, 다음과 같은 일을하는 것은 아마 더 :

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

당신은 객체를 구성하는게재 위치 새를 사용해야합니다 읽을 수 있음 :

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 

또한받은 적절한 파괴와 메모리의 해방을 처리하기 위해 사용자 정의 deleters 스마트 포인터의 사용을 탐구 할 수 있습니다 명시 적으로이 같은 객체를 소멸 기억 tbb의 메모리 할당 자

+0

이러한 방식으로 C++ 11 초기화되지 않은 저장소에 사용자 지정 할당자를 사용할 수 있습니까? – fish2000

관련 문제