【发布时间】:2020-02-14 01:59:24
【问题描述】:
我正在尝试实现自定义allocator 以将内存映射文件存储在std::vector 中。 boost::iostreams::mapped_file执行的文件映射
文件内存映射的分配器类型:
template<typename T>
class mmap_allocator
{
public:
typedef T value_type;
mmap_allocator(const std::string& filename)
: _mmfile(filename) { }
T* allocate (size_t n)
{
return reinterpret_cast<T*>(_mmfile.data());
}
void deallocate (T* p, size_t n)
{
p = nullptr;
_mmfile.close();
}
private:
boost::iostreams::mapped_file _mmfile;
};
内存映射文件的容器,基于std::vector:
//Get file size
long GetFileSize(std::string filename)
{
FILE *p_file = NULL;
p_file = fopen(filename.c_str(),"rb");
fseek(p_file,0,SEEK_END);
int size = ftell(p_file);
fclose(p_file);
return size;
}
template<typename T>
class mm_vector : public std::vector<T, mmap_allocator<T> >
{
public:
typedef mmap_allocator<T> allocator_type;
typedef std::vector<T, allocator_type > b_vector;
mm_vector(const std::string filename) : b_vector(GetFileSize(filename)/sizeof(T), allocator_type(filename))
{
b_vector::reserve(GetFileSize(filename)/sizeof(T));
}
};
测试代码:
int main()
{
mm_vector<int> v("test.f");//test.f - binary file contain several integers
for(auto x : v) std::cout<<x<<" ";
}
此代码无法正常工作 - 输出始终为零。文件包含正确的内容 - 几个整数。此代码运行良好:
boost::iostreams::mapped_file _mmfile("test.f");
int* p = (int*)(_mmfile.data());
std::cout<<p[0];
我做错了什么?
【问题讨论】:
-
GetFileSize函数中没有任何错误检查。fopen和其中的其他功能可能会失败,如果它们失败,它们会返回错误代码以告诉您出了什么问题。你应该检查它们。 -
您的 allocate() 函数总是返回相同的值。它应该像 malloc() 并在每次调用时返回差异值。
标签: c++ vector stl memory-mapped-files allocator