【问题标题】:Use Memory Pool with Custom Allocator for STL Containers将内存池与自定义分配器一起用于 STL 容器
【发布时间】:2020-03-01 06:08:04
【问题描述】:

我希望能够将需要从中分配的内存池传递给 STL 容器(vector、unordered_map 等)。我找到了this question,但它并没有解决我面临的具体问题。 我已经有一个可以在容器声明中指定的工作自定义分配器,但无法从应用程序中找到一种方法来传递分配器在内部使用的地址(通过放置新运算符)。基本上我想去

发件人:

std::vector<int, myCustomAllocator<int>> myVector;

到:

void* pool = getMemoryPoolAddress();
std::vector<int, myCustomAllocator<int>/*Specify memory pool somehow*/> myVector;

如何将pool 传递给我的分配器?

【问题讨论】:

    标签: c++11 memory-management stl dynamic-memory-allocation


    【解决方案1】:

    标准库分配器是无状态的(有关上下文,请参阅CppCon 2015: Andrei Alexandrescu “std::allocator is to Allocation what std::vector is to Vexation”)。这意味着您的具体分配器类型只能具有一种状态(单态) - 全局状态,或 C++ 中的 static

    所以您链接的问题包含您问题的答案:

    class MyPoolAlloc {
    public:
      static MyPool *pMyPool;
      ...
    };
    
    MyPool* MyPoolAlloc<T>::pMyPool = NULL;
    

    这是为分配器类型指定池的方法。

    【讨论】:

      猜你喜欢
      • 2012-02-22
      • 2012-07-07
      • 2013-05-31
      • 1970-01-01
      • 2011-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      相关资源
      最近更新 更多