summaryrefslogtreecommitdiffstats
path: root/src/boost/libs/pool/test/track_allocator.hpp
blob: ed989f04850a56bc50fdd7b429fff39ed9cae651 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/* Copyright (C) 2000, 2001 Stephen Cleary
* Copyright (C) 2011 Kwan Ting Chan
* 
* Use, modification and distribution is subject to the 
* Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
*/

#ifndef BOOST_POOL_TRACK_ALLOCATOR_HPP
#define BOOST_POOL_TRACK_ALLOCATOR_HPP

#include <boost/detail/lightweight_test.hpp>

#include <new>
#include <set>
#include <stdexcept>

#include <cstddef>

// Each "tester" object below checks into and out of the "cdtor_checker",
//  which will check for any problems related to the construction/destruction of
//  "tester" objects.
class cdtor_checker
{
private:
    // Each constructed object registers its "this" pointer into "objs"
    std::set<void*> objs;

public:
    // True iff all objects that have checked in have checked out
    bool ok() const { return objs.empty(); }

    ~cdtor_checker()
    {
        BOOST_TEST(ok());
    }

    void check_in(void * const This)
    {
        BOOST_TEST(objs.find(This) == objs.end());
        objs.insert(This);
    }

    void check_out(void * const This)
    {
        BOOST_TEST(objs.find(This) != objs.end());
        objs.erase(This);
    }
};
static cdtor_checker mem;

struct tester
{
    tester(bool throw_except = false)
    {
        if(throw_except)
        {
            throw std::logic_error("Deliberate constructor exception");
        }

        mem.check_in(this);
    }

    tester(const tester &)
    {
        mem.check_in(this);
    }

    ~tester()
    {
        mem.check_out(this);
    }
};

// Allocator that registers alloc/dealloc to/from the system memory
struct track_allocator
{
    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;

    static std::set<char*> allocated_blocks;

    static char* malloc(const size_type bytes)
    {
        char* const ret = new (std::nothrow) char[bytes];
        allocated_blocks.insert(ret);
        return ret;
    }

    static void free(char* const block)
    {
        BOOST_TEST(allocated_blocks.find(block) != allocated_blocks.end());
        allocated_blocks.erase(block);
        delete [] block;
    }

    static bool ok()
    {
        return allocated_blocks.empty();
    }
};
std::set<char*> track_allocator::allocated_blocks;

#endif // BOOST_POOL_TRACK_ALLOCATOR_HPP