使用mmap地址复制构造函数

时间:2016-06-10 06:22:47

标签: c++ mmap

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

1 个答案:

答案 0 :(得分:2)

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;

}