shared_ptr with dynamic allocated memory and with mmap-ed memory

时间:2015-07-29 00:19:48

标签: c++ c++11 shared-ptr mmap

For my project I am using " with dynamically allocated shared_ptr.

At different point I am accessing same struct, but on mmap-ed memory.

Is there some trick I can use with struct, so not to duplicate existing code? For example a custom deleter that actually does not delete?

I realize this will be still risky, but it will be done for very short period of time - inside function body and I do not want to copy the whole struct, just to run some simple function over it.

3 个答案:

答案 0 :(得分:1)

您可以使用std::shared_pointer aliasing constructor

std::shared_ptr shm;  // points at mmap'ed region, with munmap deleter
Foo *p; // somewhere within this region

auto shared_p = std::shared_ptr{p, shm};

shm生效时,这会增加shared_p的引用次数。

答案 1 :(得分:0)

经过一些研究,对于MMAP相关案例,我做了自定义删除操作,删除了任何内容。

static void null_deleter(void *){
    // null_deleter
}

...

void abc(Blob *p){
    mySharedPtr.reset(p, null_deleter);
}

答案 2 :(得分:0)

查看boost进程间库,它允许在由文件的mmap()创建的内存中创建对象。它们有一些可重定位的指针,能够指向同一个内存竞技场内的对象,并将这个竞技场映射到不同的位置。不支持的是虚拟功能表的重定位 - 他们讨论这个问题。但我认为这只适用,如果你有不同版本的可执行文件或虚拟方法表位于共享库中。