• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
9 #ifndef BOOST_POOL_TRACK_ALLOCATOR_HPP
10 #define BOOST_POOL_TRACK_ALLOCATOR_HPP
11 
12 #include <boost/detail/lightweight_test.hpp>
13 
14 #include <new>
15 #include <set>
16 #include <stdexcept>
17 
18 #include <cstddef>
19 
20 // Each "tester" object below checks into and out of the "cdtor_checker",
21 //  which will check for any problems related to the construction/destruction of
22 //  "tester" objects.
23 class cdtor_checker
24 {
25 private:
26     // Each constructed object registers its "this" pointer into "objs"
27     std::set<void*> objs;
28 
29 public:
30     // True iff all objects that have checked in have checked out
ok() const31     bool ok() const { return objs.empty(); }
32 
~cdtor_checker()33     ~cdtor_checker()
34     {
35         BOOST_TEST(ok());
36     }
37 
check_in(void * const This)38     void check_in(void * const This)
39     {
40         BOOST_TEST(objs.find(This) == objs.end());
41         objs.insert(This);
42     }
43 
check_out(void * const This)44     void check_out(void * const This)
45     {
46         BOOST_TEST(objs.find(This) != objs.end());
47         objs.erase(This);
48     }
49 };
50 static cdtor_checker mem;
51 
52 struct tester
53 {
testertester54     tester(bool throw_except = false)
55     {
56         if(throw_except)
57         {
58             throw std::logic_error("Deliberate constructor exception");
59         }
60 
61         mem.check_in(this);
62     }
63 
testertester64     tester(const tester &)
65     {
66         mem.check_in(this);
67     }
68 
~testertester69     ~tester()
70     {
71         mem.check_out(this);
72     }
73 };
74 
75 // Allocator that registers alloc/dealloc to/from the system memory
76 struct track_allocator
77 {
78     typedef std::size_t size_type;
79     typedef std::ptrdiff_t difference_type;
80 
81     static std::set<char*> allocated_blocks;
82 
malloctrack_allocator83     static char* malloc(const size_type bytes)
84     {
85         char* const ret = new (std::nothrow) char[bytes];
86         allocated_blocks.insert(ret);
87         return ret;
88     }
89 
freetrack_allocator90     static void free(char* const block)
91     {
92         BOOST_TEST(allocated_blocks.find(block) != allocated_blocks.end());
93         allocated_blocks.erase(block);
94         delete [] block;
95     }
96 
oktrack_allocator97     static bool ok()
98     {
99         return allocated_blocks.empty();
100     }
101 };
102 std::set<char*> track_allocator::allocated_blocks;
103 
104 #endif // BOOST_POOL_TRACK_ALLOCATOR_HPP
105