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