doc_erasing_and_disposing.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /////////////////////////////////////////////////////////////////////////////
  2. //
  3. // (C) Copyright Ion Gaztanaga 2006-2014
  4. //
  5. // Distributed under the Boost Software License, Version 1.0.
  6. // (See accompanying file LICENSE_1_0.txt or copy at
  7. // http://www.boost.org/LICENSE_1_0.txt)
  8. //
  9. // See http://www.boost.org/libs/intrusive for documentation.
  10. //
  11. /////////////////////////////////////////////////////////////////////////////
  12. #include <boost/core/no_exceptions_support.hpp>
  13. //[doc_erasing_and_disposing
  14. #include <boost/intrusive/list.hpp>
  15. using namespace boost::intrusive;
  16. //A class that can be inserted in an intrusive list
  17. class my_class : public list_base_hook<>
  18. {
  19. public:
  20. my_class(int i)
  21. : int_(i)
  22. {}
  23. int int_;
  24. //...
  25. };
  26. //Definition of the intrusive list
  27. typedef list<my_class> my_class_list;
  28. //The predicate function
  29. struct is_even
  30. {
  31. bool operator()(const my_class &c) const
  32. { return 0 == (c.int_ % 2); }
  33. };
  34. //The disposer object function
  35. struct delete_disposer
  36. {
  37. void operator()(my_class *delete_this)
  38. { delete delete_this; }
  39. };
  40. int main()
  41. {
  42. const int MaxElem = 100;
  43. //Fill all the nodes and insert them in the list
  44. my_class_list list;
  45. //<-
  46. #if 1
  47. BOOST_TRY{
  48. #else
  49. //->
  50. try{
  51. //<-
  52. #endif
  53. //->
  54. //Insert new objects in the container
  55. for(int i = 0; i < MaxElem; ++i) list.push_back(*new my_class(i));
  56. //Now use remove_and_dispose_if to erase and delete the objects
  57. list.remove_and_dispose_if(is_even(), delete_disposer());
  58. }
  59. //<-
  60. #if 1
  61. BOOST_CATCH(...){
  62. #else
  63. //->
  64. catch(...){
  65. //<-
  66. #endif
  67. //->
  68. //If something throws, make sure that all the memory is freed
  69. list.clear_and_dispose(delete_disposer());
  70. //<-
  71. #if 1
  72. BOOST_RETHROW
  73. #else
  74. //->
  75. throw;
  76. //<-
  77. #endif
  78. //->
  79. }
  80. //<-
  81. BOOST_CATCH_END
  82. //->
  83. //Dispose remaining elements
  84. list.erase_and_dispose(list.begin(), list.end(), delete_disposer());
  85. return 0;
  86. }
  87. //]