given these types (from here, more or less):
typedef boost::interprocess::managed_shared_memory::segment_manager SegmentManager;
typedef boost::interprocess::allocator<char, SegmentManager> CharAllocator;
typedef boost::interprocess::basic_string<char, std::char_traits<char>, CharAllocator> ShmString;
typedef boost::interprocess::allocator<ShmString, SegmentManager> StringAllocator;
typedef boost::interprocess::vector<ShmString, StringAllocator> ShmStringVector;
Whenever I retrieve a ShmString from the ShmStringVector
, the free size of my shared memory segment goes down.
What I think is happening is whenever ShmString
is constructed, even as a stack variable, it allocates space inside the shared memory segment.
When that ShmString
goes out of scope, the memory gets returned. But if I'm close to capacity on my segment, I don't want accesses risking causing an overrun on the shared memory segment.
How can I get the string out without triggering another allocation?
In the example below, I tried
//shared mem segment previously created with 1,000,000 bytes allocated
managed_shared_memory segment(open_only, "somename");
CharAllocator charAllocator(segment.get_segment_manager());
ShmStringVector *vec = segment.find<ShmStringVector>("somevectorname").first;
vec->push_back(" ... big string ..." ); // I can push a const char*
size_t sizeAfterInsertion = segment.get_free_memory();
ShmString res1 = vec->at(0); //works, but steals memory from shared memory, at least temporarily !
const char* res2 = vec->at(0); //compiler error
std::string res3 = vec->at(0); //compiler error
size_t sizeAfterGet = segment2.get_free_memory();
size_t diff = sizeAfterInsertion - sizeAfterGet;
I proved to myself memory was being taken by declaring ShmString
...
std::string size 170,
before ins: 999232, after ins: 998976, shared memory taken by ins: 256
after get: 998768, shared memory taken by get: 208