我正在研究一个 mmap 分配器,它允许向量使用来自
内存映射文件。目标是拥有使用存储的向量
直接在mmap映射的虚拟内存中。我们的问题是
改进将非常大的文件 (>10GB) 读取到内存中而无需复制
开销,因此我需要这个自定义分配器。
到目前为止,我有一个自定义分配器的骨架
(源自 std::allocator),我认为这是一个好的开始
指向编写自己的分配器。随意使用这段代码
以任何你想要的方式:
#include <memory>
#include <stdio.h>
namespace mmap_allocator_namespace
{
// See StackOverflow replies to this answer for important commentary about inheriting from std::allocator before replicating this code.
template <typename T>
class mmap_allocator: public std::allocator<T>
{
public:
typedef size_t size_type;
typedef T* pointer;
typedef const T* const_pointer;
template<typename _Tp1>
struct rebind
{
typedef mmap_allocator<_Tp1> other;
};
pointer allocate(size_type n, const void *hint=0)
{
fprintf(stderr, "Alloc %d bytes.\n", n*sizeof(T));
return std::allocator<T>::allocate(n, hint);
}
void deallocate(pointer p, size_type n)
{
fprintf(stderr, "Dealloc %d bytes (%p).\n", n*sizeof(T), p);
return std::allocator<T>::deallocate(p, n);
}
mmap_allocator() throw(): std::allocator<T>() { fprintf(stderr, "Hello allocator!\n"); }
mmap_allocator(const mmap_allocator &a) throw(): std::allocator<T>(a) { }
template <class U>
mmap_allocator(const mmap_allocator<U> &a) throw(): std::allocator<T>(a) { }
~mmap_allocator() throw() { }
};
}
要使用它,请按如下方式声明一个 STL 容器:
using namespace std;
using namespace mmap_allocator_namespace;
vector<int, mmap_allocator<int> > int_vec(1024, 0, mmap_allocator<int>());
它可以用于例如在分配内存时记录。什么是必要的
是重新绑定结构,否则向量容器使用超类分配/解除分配
方法。
更新:内存映射分配器现在可在 https://github.com/johannesthoma/mmap_allocator 获得,并且是 LGPL。随意将它用于您的项目。