I'm trying to implement custom allocator
for storing memory mapped files in the std::vector
. Files mapping performed by boost::iostreams::mapped_file
Allocator type for file memory mapping:
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;
};
Container for memory mapped file, based on 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));
}
};
Test code:
int main()
{
mm_vector<int> v("test.f");//test.f - binary file contain several integers
for(auto x : v) std::cout<<x<<" ";
}
This code don't work properly - output always equals to zero. File contains correct content - several integers. This code works well:
boost::iostreams::mapped_file _mmfile("test.f");
int* p = (int*)(_mmfile.data());
std::cout<<p[0];
What am I doing wrong?