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
#ifndef OBJECT_POOL_H
#define OBJECT_POOL_H
#include <assert.h>

#include <string>
#include <vector>

#include <vector>
using namespace std;

template <class T>
class ObjectPool {
    struct Pool;
public:

    ObjectPool() {
        chunkSize = 1;
    }

    virtual ~ObjectPool() {
    }

    void setChunkSize(size_t n) {
        chunkSize = n;
    }

    void reserve(size_t n) {
        Pool *p = new Pool(n);
        vpools.push_back(p);
    }

    T *allocate() {
        Pool *p;
        if (!vpools.empty()) {
            p = vpools.back();
            if (!p->is_filled()) return p->allocate();
        }

        // Resources exhausted, create new pool..
        p = new Pool(chunkSize);
        vpools.push_back(p);

        return p->allocate();
    }

    void release(T *obj) {
    }

    int deleteAll() {
        for (size_t i = 0; i < vpools.size(); i++) {
            vpools[i]->deleteAll();
            delete vpools[i];
        }
        vpools.clear();
        return 0;
    }
private:
    size_t chunkSize;

    struct Pool {<--- 'struct Pool' does not have a copy constructor which is recommended since the class contains a pointer to allocated memory.

        Pool(size_t n) {
            currpos = 0;
            capacity = n;
            objects = new T[capacity];
            assert(objects != NULL);
        }

        bool is_filled() const {
            return currpos == capacity;
        }

        T * allocate() {
            return &objects[currpos++];
        }

        void deleteAll() {
            capacity = 0;
            currpos = 0;
            delete [] objects;
            objects = NULL;
        }

        size_t capacity, currpos;
        T *objects;
    };

    std::vector<Pool*> vpools;
};

#endif