简体   繁体   English

具有动态分配的内存和mmap-ed内存的shared_ptr

[英]shared_ptr with dynamic allocated memory and with mmap-ed memory

For my project I am using shared_ptr with dynamically allocated struct . 对于我的项目,我将使用shared_ptr和动态分配的struct

At different point I am accessing same struct , but on mmap-ed memory. 在不同的位置,我正在访问相同的struct ,但是在mmap-ed内存上。

Is there some trick I can use with shared_ptr , so not to duplicate existing code? 我可以使用一些技巧与shared_ptr使用,以免复制现有代码吗? 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. 我意识到这仍然是有风险的,但是它将在很短的时间内完成-在函数体内,我不想复制整个结构,而只是在它上面运行一些简单的函数。

You can use the aliasing constructor of std::shared_pointer : 您可以使用std::shared_pointer别名构造函数

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};

This will increase the reference count of shm while shared_p is live. shared_p处于活动状态时,这将增加shm的引用计数。

After some research, for MMAP related case, I did custom deleter that delete nothing. 经过一些研究,对于与MMAP有关的情况,我做了自定义删除程序,它什么也不删除。

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

...

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

check out the boost interprocess library which allows creating objects in memory created by mmap() of a file. 请检查boost-interprocess库,该库允许在文件的mmap()创建的内存中创建对象。 They have some relocateable pointer, to be able to point to objects inside the same memory arena and map this arena at different locations. 它们具有一些可重定位的指针,以便能够指向同一内存区域内的对象并将该区域映射到不同的位置。 What is not supported is relocation of virtual function tables -- they discuss this. 不支持虚拟函数表的重定位-他们对此进行了讨论。 But I think this would only apply, if you either have different versions of an executable or the virtual method table is located inside a shared library. 但是我认为这仅适用于以下情况:具有不同版本的可执行文件,或者虚拟方法表位于共享库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM