doc_clone_from.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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_clone_from
  13. #include <boost/intrusive/list.hpp>
  14. #include <iostream>
  15. #include <vector>
  16. using namespace boost::intrusive;
  17. //A class that can be inserted in an intrusive list
  18. class my_class : public list_base_hook<>
  19. {
  20. public:
  21. friend bool operator==(const my_class &a, const my_class &b)
  22. { return a.int_ == b.int_; }
  23. int int_;
  24. //...
  25. };
  26. //Definition of the intrusive list
  27. typedef list<my_class> my_class_list;
  28. //Cloner object function
  29. struct new_cloner
  30. {
  31. my_class *operator()(const my_class &clone_this)
  32. { return new my_class(clone_this); }
  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. std::vector<my_class> nodes(MaxElem);
  44. //Fill all the nodes and insert them in the list
  45. my_class_list list;
  46. for(int i = 0; i < MaxElem; ++i) nodes[i].int_ = i;
  47. list.insert(list.end(), nodes.begin(), nodes.end());
  48. //Now clone "list" using "new" and "delete" object functions
  49. my_class_list cloned_list;
  50. cloned_list.clone_from(list, new_cloner(), delete_disposer());
  51. //Test that both are equal
  52. if(cloned_list != list)
  53. std::cout << "Both lists are different" << std::endl;
  54. else
  55. std::cout << "Both lists are equal" << std::endl;
  56. //Don't forget to free the memory from the second list
  57. cloned_list.clear_and_dispose(delete_disposer());
  58. return 0;
  59. }
  60. //]