【问题标题】:How to set allocator for dynamically allocated stl container?如何为动态分配的 stl 容器设置分配器?
【发布时间】:2016-09-16 22:14:41
【问题描述】:

我正在使用 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,然后分配一个自定义分配器?

【问题讨论】:

    标签: c++ c++11 memory-management tbb


    【解决方案1】:

    这样做之后:

    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++11 未初始化存储与自定义分配器一起使用吗?
    猜你喜欢
    • 2020-08-10
    • 2012-09-23
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    • 2015-03-12
    相关资源
    最近更新 更多