简体   繁体   中英

shared_ptr with dynamic allocated memory and with mmap-ed memory

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

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

Is there some trick I can use with shared_ptr , 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.

You can use the aliasing constructor of 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.

After some research, for MMAP related case, I did custom deleter that delete nothing.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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