使用 mmap 地址复制构造函数

Copy Constructor with mmap address

当class有一个mmap地址指针时,是否可以有一个复制构造函数?我在想 mmap 只被调用过一次,所以内核只注册了一个引用。现在两个对象共享那个地址,当 1 被删除时那个地址会发生什么?我想那是清理过的。如果可能,mmap 文件会为我处理同步吗?

shared_ptr 是你的朋友:

#include <sys/mman.h>
#include <memory>


std::shared_ptr<void> map_some_memory(void *addr, size_t length, 
                                      int prot, int flags,
                                      int fd, off_t offset)
{
  auto deleter = [length](void* p) {
    munmap(p, length);
  };

  // use of a custom deleter ensures that the mmap call is undone
  // when the last reference to the memory goes away.

  return { mmap(addr, length, prot, flags, fd, offset), deleter };

}

// some function that gets you a file descriptor
extern int alloc_fd();

int main()
{
  int some_file = alloc_fd();

  // allocate a shared mapping
  auto my_mapped_ptr = map_some_memory(nullptr, 100, PROT_READ | PROT_WRITE,
                                       MAP_SHARED, some_file, 0);

  // cast it to sometthing else

  auto shared_ints = std::shared_ptr<int>(my_mapped_ptr, 
                                          reinterpret_cast<int*>(my_mapped_ptr.get()));

  // another shared pointer pointing to the shared ints
  auto another_share = shared_ints;

}