将内存池与自定义分配器一起用于STL容器

问题描述 投票:0回答:1

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

发件人:

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个回答
0
投票

标准库分配器是无状态的(有关上下文,请参见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;

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

© www.soinside.com 2019 - 2024. All rights reserved.