Boost logo

Boost Users :

From: i.nixman_at_[hidden]
Date: 2021-07-12 14:25:46


hi guys!

I want to use boost::interprocess to store some resources (strings) into
`bi::map<bi::string, bi::string>` that uses `bi::managed_mapped_file` so
I can put the resources in the map once, take the file, and distribute
it with the program.

the problem is that I cannot calculate the required size in advance, so
I want to use `bi::managed_mapped_file::grow ()` before inserting
another element into the map.
but it doesn't work as i expected, at some point i get exception:
what(): boost::interprocess::bad_alloc

I know the length of the key string and the length of the value string,
how can I find out the size by which I must `grow()` before inserting
another element into the map?

now my code looks like this:

#include <boost/interprocess/managed_mapped_file.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/map.hpp>
#include <boost/interprocess/containers/string.hpp>

#include <iostream>

int main () {
     namespace bi = boost::interprocess;

     using segment_manager_t = bi::managed_mapped_file::segment_manager;

     using void_allocator = bi::allocator<void, segment_manager_t>;
     using char_allocator = bi::allocator<char, segment_manager_t>;

     using char_string = bi::basic_string<char, std::char_traits<char>,
char_allocator>;

     using map_value_type = std::pair<const char_string, char_string>;
     using map_value_type_allocator = bi::allocator<map_value_type,
segment_manager_t>;

     using map_type = bi::map<char_string, char_string,
std::less<char_string>, map_value_type_allocator>;

     static const char *mapfname = "map.dat";
     bi::managed_mapped_file mmfile(bi::open_or_create, mapfname, 1024);
     {
         void_allocator alloc_inst(mmfile.get_segment_manager());

         map_type *mymap =
mmfile.find_or_construct<map_type>("MyMap")(alloc_inst);
         assert(mymap);

         for ( int i = 0; i < 100; ++i ) {
             std::string s = std::to_string(i);

             char_string key(s.c_str(), alloc_inst);
             char_string value(s.c_str(), alloc_inst);

              // bi::managed_mapped_file::grow(mapfname, ???);
<<<<<<<<<<<<<<<<<<<<<<

             mymap->emplace(std::move(key), std::move(value));
         }
     }

     bi::managed_mapped_file::shrink_to_fit(mapfname);

     return 0;
}

(or: https://wandbox.org/permlink/jtTOzlMh16ZS8jG6)

any ideas?

best!


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net