Search code examples
c++stdvectormmap

How to encapsulate a memory-mapped file into a std::vector?


In C++, on Linux, after I open a file with open() and then memory-map it with mmap(), I am given a void* that I can typecast to e.g. char* and read as desired.

But, suppose I want to use std::vector to access that data. How could I accomplish that?

At first I thought I could make a custom allocator for my std::vector. But I see two problems with that:

  1. Its allocate() method will only receive a size argument. That is insufficient, as it also needs to know the already-mapped address, rather than allocating a new one (as allocators usually do.)
  2. Its deallocate() method -- to do this correctly -- would need to both unmap the buffer (easy, once #1 above is solved,) and close() the file descriptor (hard, since it has no way of knowing that value.)

I thought about maybe storing this metadata (existing mapped address, and file descriptor) in a known place to be referenced by my custom allocator, but that would not be thread-safe without complicating things with TLS.

Is the above possible some way? Or ill-advised (if so, please explain)? Is there perhaps some other standard-library class that would serve my purpose?

My reason for wanting to do this, is to avoid a raw/POD pointer in a class that interprets the binary data in that memory-mapped region.


Solution

  • Is there perhaps some other standard-library class that would serve my purpose?

    Yes: std::span is a wrapper that provides container like access without ownership.