Boost logo

Boost Users :

From: Ion Gaztañaga (igaztanaga_at_[hidden])
Date: 2007-01-23 16:37:03


Hi,

Wolfgang Hottgenroth wrote:
> Hi,
[snip]
>
> To put pair into the map I wrote:
>
> typedef boost::interprocess::allocator<char,
> boost::interprocess::managed_shared_memory::segment_manager>
> ShmemStringAllocator;
> typedef boost::interprocess::basic_string<char, char_traits<char>,
> ShmemStringAllocator> MyString;
>
> MyString key(segment.get_segment_manager());
> MyString value(segment.get_segment_manager());
>
> key = "key1";
> value = "value1";
>
> mymap->insert(std::pair<MyString, MyString>(key, value));
>
> (For the complete code see http://www.hottis.de/boost/strings/. Thanks.)
>
> What I'm wondering is: will the memory required for key and value be
> freed automatically in the writing process (put.C)?

If you refer to the local "key" and "value" variables, the string
objects (the class that contains a pointer to a dynamically allocated
object) are allocated in your process' stack, but the dynamically
allocated buffers holding "key1" and "value1" are allocated in shared
memory. When "key" and "value" go out of scope, memory is automatically
reclaimed. Just like std::string. The difference is that std::string
allocates the internal buffer calling std::allocator::allocate (that is,
operator new[]), whereas boost::interprocess::allocator will allocate
the string from shared memory (using
boost::interprocess::allocator::allocate). But anyway, when the object
is destroyed, memory is freed.

> When I like to erase an element from the map, do I need to do more than
> just calling mymap->erase(key)?

No. That's all. All the dynamic memory from the strings (allocated in
the shared memory segment) is also freed.

> And finally when I'm done and like to remove the whole map, is more
> required than segment.destroy<MyMap>("MyMap")? Will all the MyString's
> in the map go too?

Yes. All will be automatically freed.

> Furthermore: is it possible to use a map in shared memory as an
> associative array and write:
>
> MyString value = (*mymap)[key];
>
> It doesn't compile for me.

The problem when using operator[], is that the mapped type must be
default constructible. And boost::interprocess::basic_string, needs the
allocator argument. You will need to use insert, sorry.

> Thanks,
> Wolfgang

Regards,

Ion


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