How to use mmap to point to STL type?

喜夏-厌秋 提交于 2019-12-08 04:18:19

问题


I have a mmap typecast to a char pointer

char *ptr;

ptr = (char *)mmap(0, FILESIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

This was my earlier code. But now I want to use a map instead of char * as the requirements changed.

Now, my map is declared as map < int, string > i_s_map;

How do I change my mmap call to point to the map?


回答1:


You don't want to store STL containers in shared memory, at least not share them. The reason is that they rely heavily on heap allocation, so out-of-the-box std::map will hold pointers from virtual address space of a different process.

Take a look at boost::interprocess for a way to deal with this situation in C++.




回答2:


If you want to create a map object in the memory returned by mmap use placement new.

map<int,string> *i_s_map = new(ptr) map<int,string>();

That will create the map object itself in the memory. In order to get the elements inside the map into the memory, you will need to create a custom allocator to keep the data in the memory. You can use the boost interprocess library for some allocators which work inside shared memory.

http://www.boost.org/doc/libs/1_42_0/doc/html/interprocess/allocators_containers.html#interprocess.allocators_containers.allocator_introduction



来源:https://stackoverflow.com/questions/2650034/how-to-use-mmap-to-point-to-stl-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!