doc_managed_heap_memory.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. //////////////////////////////////////////////////////////////////////////////
  2. //
  3. // (C) Copyright Ion Gaztanaga 2006-2012. Distributed under the Boost
  4. // Software License, Version 1.0. (See accompanying file
  5. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // See http://www.boost.org/libs/interprocess for documentation.
  8. //
  9. //////////////////////////////////////////////////////////////////////////////
  10. #include <boost/interprocess/detail/config_begin.hpp>
  11. #include <boost/interprocess/detail/workaround.hpp>
  12. //[doc_managed_heap_memory
  13. #include <boost/interprocess/containers/list.hpp>
  14. #include <boost/interprocess/managed_heap_memory.hpp>
  15. #include <boost/interprocess/allocators/allocator.hpp>
  16. #include <cstddef>
  17. using namespace boost::interprocess;
  18. typedef list<int, allocator<int, managed_heap_memory::segment_manager> >
  19. MyList;
  20. int main ()
  21. {
  22. //We will create a buffer of 1000 bytes to store a list
  23. managed_heap_memory heap_memory(1000);
  24. MyList * mylist = heap_memory.construct<MyList>("MyList")
  25. (heap_memory.get_segment_manager());
  26. //Obtain handle, that identifies the list in the buffer
  27. managed_heap_memory::handle_t list_handle = heap_memory.get_handle_from_address(mylist);
  28. //Fill list until there is no more memory in the buffer
  29. try{
  30. while(1) {
  31. mylist->insert(mylist->begin(), 0);
  32. }
  33. }
  34. catch(const bad_alloc &){
  35. //memory is full
  36. }
  37. //Let's obtain the size of the list
  38. MyList::size_type old_size = mylist->size();
  39. //<-
  40. (void)old_size;
  41. //->
  42. //To make the list bigger, let's increase the heap buffer
  43. //in 1000 bytes more.
  44. heap_memory.grow(1000);
  45. //If memory has been reallocated, the old pointer is invalid, so
  46. //use previously obtained handle to find the new pointer.
  47. mylist = static_cast<MyList *>
  48. (heap_memory.get_address_from_handle(list_handle));
  49. //Fill list until there is no more memory in the buffer
  50. try{
  51. while(1) {
  52. mylist->insert(mylist->begin(), 0);
  53. }
  54. }
  55. catch(const bad_alloc &){
  56. //memory is full
  57. }
  58. //Let's obtain the new size of the list
  59. MyList::size_type new_size = mylist->size();
  60. //<-
  61. (void)new_size;
  62. //->
  63. assert(new_size > old_size);
  64. //Destroy list
  65. heap_memory.destroy_ptr(mylist);
  66. return 0;
  67. }
  68. //]
  69. #include <boost/interprocess/detail/config_end.hpp>