doc_auto_unlink.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /////////////////////////////////////////////////////////////////////////////
  2. //
  3. // (C) Copyright Ion Gaztanaga 2006-2013
  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. //[doc_auto_unlink_code
  13. #include <boost/intrusive/list.hpp>
  14. #include <cassert>
  15. using namespace boost::intrusive;
  16. typedef list_base_hook<link_mode<auto_unlink> > auto_unlink_hook;
  17. class MyClass : public auto_unlink_hook
  18. //This hook removes the node in the destructor
  19. {
  20. int int_;
  21. public:
  22. MyClass(int i = 0) : int_(i) {}
  23. int get_int() { return int_; }
  24. void unlink() { auto_unlink_hook::unlink(); }
  25. bool is_linked() { return auto_unlink_hook::is_linked(); }
  26. };
  27. //Define a list that will store values using the base hook
  28. //The list can't have constant-time size!
  29. typedef list< MyClass, constant_time_size<false> > List;
  30. int main()
  31. {
  32. //Create the list
  33. List l;
  34. {
  35. //Create myclass and check it's linked
  36. MyClass myclass;
  37. assert(myclass.is_linked() == false);
  38. //Insert the object
  39. l.push_back(myclass);
  40. //Check that we have inserted the object
  41. assert(l.empty() == false);
  42. assert(&l.front() == &myclass);
  43. assert(myclass.is_linked() == true);
  44. //Now myclass' destructor will unlink it
  45. //automatically
  46. }
  47. //Check auto-unlink has been executed
  48. assert(l.empty() == true);
  49. {
  50. //Now test the unlink() function
  51. //Create myclass and check it's linked
  52. MyClass myclass;
  53. assert(myclass.is_linked() == false);
  54. //Insert the object
  55. l.push_back(myclass);
  56. //Check that we have inserted the object
  57. assert(l.empty() == false);
  58. assert(&l.front() == &myclass);
  59. assert(myclass.is_linked() == true);
  60. //Now unlink the node
  61. myclass.unlink();
  62. //Check auto-unlink has been executed
  63. assert(l.empty() == true);
  64. }
  65. return 0;
  66. }
  67. //]