shared_ptr_example.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // Boost shared_ptr_example.cpp --------------------------------------------//
  2. // Copyright Beman Dawes 2001. Distributed under the Boost
  3. // Software License, Version 1.0. (See accompanying file
  4. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. // See http://www.boost.org/libs/smart_ptr for documentation.
  6. // Revision History
  7. // 21 May 01 Initial complete version (Beman Dawes)
  8. // The original code for this example appeared in the shared_ptr documentation.
  9. // Ray Gallimore pointed out that foo_set was missing a Compare template
  10. // argument, so would not work as intended. At that point the code was
  11. // turned into an actual .cpp file so it could be compiled and tested.
  12. #include <vector>
  13. #include <set>
  14. #include <iostream>
  15. #include <algorithm>
  16. #include <boost/shared_ptr.hpp>
  17. // The application will produce a series of
  18. // objects of type Foo which later must be
  19. // accessed both by occurrence (std::vector)
  20. // and by ordering relationship (std::set).
  21. struct Foo
  22. {
  23. Foo( int _x ) : x(_x) {}
  24. ~Foo() { std::cout << "Destructing a Foo with x=" << x << "\n"; }
  25. int x;
  26. /* ... */
  27. };
  28. typedef boost::shared_ptr<Foo> FooPtr;
  29. struct FooPtrOps
  30. {
  31. bool operator()( const FooPtr & a, const FooPtr & b )
  32. { return a->x > b->x; }
  33. void operator()( const FooPtr & a )
  34. { std::cout << a->x << "\n"; }
  35. };
  36. int main()
  37. {
  38. std::vector<FooPtr> foo_vector;
  39. std::set<FooPtr,FooPtrOps> foo_set; // NOT multiset!
  40. FooPtr foo_ptr( new Foo( 2 ) );
  41. foo_vector.push_back( foo_ptr );
  42. foo_set.insert( foo_ptr );
  43. foo_ptr.reset( new Foo( 1 ) );
  44. foo_vector.push_back( foo_ptr );
  45. foo_set.insert( foo_ptr );
  46. foo_ptr.reset( new Foo( 3 ) );
  47. foo_vector.push_back( foo_ptr );
  48. foo_set.insert( foo_ptr );
  49. foo_ptr.reset ( new Foo( 2 ) );
  50. foo_vector.push_back( foo_ptr );
  51. foo_set.insert( foo_ptr );
  52. std::cout << "foo_vector:\n";
  53. std::for_each( foo_vector.begin(), foo_vector.end(), FooPtrOps() );
  54. std::cout << "\nfoo_set:\n";
  55. std::for_each( foo_set.begin(), foo_set.end(), FooPtrOps() );
  56. std::cout << "\n";
  57. // Expected output:
  58. //
  59. // foo_vector:
  60. // 2
  61. // 1
  62. // 3
  63. // 2
  64. //
  65. // foo_set:
  66. // 3
  67. // 2
  68. // 1
  69. //
  70. // Destructing a Foo with x=2
  71. // Destructing a Foo with x=1
  72. // Destructing a Foo with x=3
  73. // Destructing a Foo with x=2
  74. return 0;
  75. }