其他分享
首页 > 其他分享> > c – 如何为动态分配的stl容器设置allocator?

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

作者:互联网

我正在使用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>));

问题是设置分配器是在构造函数中. 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,然后分配一个自定义分配器?

解决方法:

这样做之后:

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

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

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

编辑

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

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

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

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

标签:c,c11,memory-management,tbb
来源: https://codeday.me/bug/20190824/1703114.html