track_allocator.hpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /* Copyright (C) 2000, 2001 Stephen Cleary
  2. * Copyright (C) 2011 Kwan Ting Chan
  3. *
  4. * Use, modification and distribution is subject to the
  5. * Boost Software License, Version 1.0. (See accompanying
  6. * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
  7. */
  8. #ifndef BOOST_POOL_TRACK_ALLOCATOR_HPP
  9. #define BOOST_POOL_TRACK_ALLOCATOR_HPP
  10. #include <boost/detail/lightweight_test.hpp>
  11. #include <new>
  12. #include <set>
  13. #include <stdexcept>
  14. #include <cstddef>
  15. // Each "tester" object below checks into and out of the "cdtor_checker",
  16. // which will check for any problems related to the construction/destruction of
  17. // "tester" objects.
  18. class cdtor_checker
  19. {
  20. private:
  21. // Each constructed object registers its "this" pointer into "objs"
  22. std::set<void*> objs;
  23. public:
  24. // True iff all objects that have checked in have checked out
  25. bool ok() const { return objs.empty(); }
  26. ~cdtor_checker()
  27. {
  28. BOOST_TEST(ok());
  29. }
  30. void check_in(void * const This)
  31. {
  32. BOOST_TEST(objs.find(This) == objs.end());
  33. objs.insert(This);
  34. }
  35. void check_out(void * const This)
  36. {
  37. BOOST_TEST(objs.find(This) != objs.end());
  38. objs.erase(This);
  39. }
  40. };
  41. static cdtor_checker mem;
  42. struct tester
  43. {
  44. tester(bool throw_except = false)
  45. {
  46. if(throw_except)
  47. {
  48. throw std::logic_error("Deliberate constructor exception");
  49. }
  50. mem.check_in(this);
  51. }
  52. tester(const tester &)
  53. {
  54. mem.check_in(this);
  55. }
  56. ~tester()
  57. {
  58. mem.check_out(this);
  59. }
  60. };
  61. // Allocator that registers alloc/dealloc to/from the system memory
  62. struct track_allocator
  63. {
  64. typedef std::size_t size_type;
  65. typedef std::ptrdiff_t difference_type;
  66. static std::set<char*> allocated_blocks;
  67. static char* malloc(const size_type bytes)
  68. {
  69. char* const ret = new (std::nothrow) char[bytes];
  70. allocated_blocks.insert(ret);
  71. return ret;
  72. }
  73. static void free(char* const block)
  74. {
  75. BOOST_TEST(allocated_blocks.find(block) != allocated_blocks.end());
  76. allocated_blocks.erase(block);
  77. delete [] block;
  78. }
  79. static bool ok()
  80. {
  81. return allocated_blocks.empty();
  82. }
  83. };
  84. std::set<char*> track_allocator::allocated_blocks;
  85. #endif // BOOST_POOL_TRACK_ALLOCATOR_HPP