我已经实现了一个基于 c++ 标准分配器接口的内存池。
template <typename T, size_t Cap = 8>
class SingularAllocator {
// member declarations ...
public:
inline SingularAllocator(); // Constructor.
inline ~SingularAllocator(); // Destructor.
inline T* allocate(const size_t n=1) ; // Allocate an entry of type T.
inline void deallocate(T*, const size_t n=1); // Deallocate an entry of type T.
template <typename... ArgsT>
inline void construct(T*, ArgsT&&...); // Construct an item.
inline void destroy(T*); // Destroy an item.
private:
thread_local Mempool _slot;
// member implementations ...
}
为简单起见,上面的代码片段只显示了界面。这个想法是使用thread_local
关键字为每个线程启用一个内存池。我的问题是如何使用它boost::variant
从我的池中创建每个对象?对于 STL 之类std::vector
的,它非常简单,因为模板参数需要一个额外的分配器字段。但是,我没有在boost::variant
.
boost::variant<int, string, OtherClass> MyStuf; // How to create this variant from my memory pool (per-thread).