simple_test.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. //
  2. // Boost.Pointer Container
  3. //
  4. // Copyright Thorsten Ottosen 2003-2005. Use, modification and
  5. // distribution is subject to the Boost Software License, Version
  6. // 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  7. // http://www.boost.org/LICENSE_1_0.txt)
  8. //
  9. // For more information, see http://www.boost.org/libs/ptr_container/
  10. //
  11. #include <boost/ptr_container/ptr_vector.hpp>
  12. #include <boost/shared_ptr.hpp>
  13. #include <boost/lambda/lambda.hpp>
  14. #include <algorithm>
  15. using namespace std;
  16. //
  17. // A simple polymorphic class
  18. //
  19. class Poly
  20. {
  21. int i_;
  22. static int cnt_;
  23. public:
  24. Poly() : i_( cnt_++ ) { }
  25. virtual ~Poly() { }
  26. void foo() { doFoo(); }
  27. private:
  28. virtual void doFoo() { ++i_; }
  29. public:
  30. friend inline bool operator>( const Poly& l, const Poly r )
  31. {
  32. return l.i_ > r.i_;
  33. }
  34. };
  35. int Poly::cnt_ = 0;
  36. //
  37. // Normally we need something like this to compare pointers to objects
  38. //
  39. template< typename T >
  40. struct sptr_greater
  41. {
  42. bool operator()( const boost::shared_ptr<T>& l, const boost::shared_ptr<T>& r ) const
  43. {
  44. return *l > *r;
  45. }
  46. };
  47. //
  48. // one doesn't need to introduce new names or live with long ones
  49. //
  50. typedef boost::shared_ptr<Poly> PolyPtr;
  51. void simple_test()
  52. {
  53. enum { size = 2000 };
  54. typedef vector<PolyPtr> vector_t;
  55. typedef boost::ptr_vector<Poly> ptr_vector_t;
  56. vector_t svec;
  57. ptr_vector_t pvec;
  58. for( int i = 0; i < size; ++i )
  59. {
  60. svec.push_back( PolyPtr( new Poly ) );
  61. pvec.push_back( new Poly ); // no extra syntax
  62. }
  63. for( int i = 0; i < size; ++i )
  64. {
  65. svec[i]->foo();
  66. pvec[i].foo(); // automatic indirection
  67. svec[i] = PolyPtr( new Poly );
  68. pvec.replace( i, new Poly ); // direct pointer assignment not possible, original element is deleted
  69. }
  70. for( vector_t::iterator i = svec.begin(); i != svec.end(); ++i )
  71. (*i)->foo();
  72. for( ptr_vector_t::iterator i = pvec.begin(); i != pvec.end(); ++i )
  73. i->foo(); // automatic indirection
  74. }
  75. #include <boost/test/unit_test.hpp>
  76. using boost::unit_test::test_suite;
  77. test_suite* init_unit_test_suite( int argc, char* argv[] )
  78. {
  79. test_suite* test = BOOST_TEST_SUITE( "Pointer Container Test Suite" );
  80. test->add( BOOST_TEST_CASE( &simple_test ) );
  81. return test;
  82. }