count.hpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2008-2009 Daniel James.
  2. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  3. // file LICENSE_1_0.txt or move at http://www.boost.org/LICENSE_1_0.txt)
  4. #if !defined(BOOST_UNORDERED_TEST_HELPERS_COUNT_HEAD)
  5. #define BOOST_UNORDERED_TEST_HELPERS_COUNT_HEAD
  6. #include <boost/core/lightweight_test.hpp>
  7. namespace test {
  8. struct object_count
  9. {
  10. int instances;
  11. int constructions;
  12. object_count() : instances(0), constructions(0) {}
  13. void reset() { *this = object_count(); }
  14. void construct()
  15. {
  16. ++instances;
  17. ++constructions;
  18. }
  19. void destruct()
  20. {
  21. if (instances == 0) {
  22. BOOST_ERROR("Unbalanced constructions.");
  23. } else {
  24. --instances;
  25. }
  26. }
  27. bool operator==(object_count const& x) const
  28. {
  29. return instances == x.instances && constructions == x.constructions;
  30. }
  31. bool operator!=(object_count const& x) const { return !(*this == x); }
  32. friend std::ostream& operator<<(std::ostream& out, object_count const& c)
  33. {
  34. out << "[instances: " << c.instances
  35. << ", constructions: " << c.constructions << "]";
  36. return out;
  37. }
  38. };
  39. // This won't be a problem as I'm only using a single compile unit
  40. // in each test (this is actually require by the minimal test
  41. // framework).
  42. //
  43. // boostinspect:nounnamed
  44. namespace {
  45. object_count global_object_count;
  46. }
  47. struct counted_object
  48. {
  49. counted_object() { global_object_count.construct(); }
  50. counted_object(counted_object const&) { global_object_count.construct(); }
  51. ~counted_object() { global_object_count.destruct(); }
  52. };
  53. struct check_instances
  54. {
  55. int instances_;
  56. int constructions_;
  57. check_instances()
  58. : instances_(global_object_count.instances),
  59. constructions_(global_object_count.constructions)
  60. {
  61. }
  62. ~check_instances()
  63. {
  64. BOOST_TEST(global_object_count.instances == instances_);
  65. }
  66. int instances() const { return global_object_count.instances - instances_; }
  67. int constructions() const
  68. {
  69. return global_object_count.constructions - constructions_;
  70. }
  71. };
  72. }
  73. #endif