TDME2 1.9.121
Pool.h
Go to the documentation of this file.
1
2#pragma once
3
4#include <vector>
5
6#include <tdme/tdme.h>
8
9using std::vector;
10
11namespace tdme {
12namespace utilities {
13
14/**
15 * Pool template class
16 * @author Andreas Drewke
17 * @version $Id$
18 * @param<E>
19 */
20template<typename T>
21class Pool
22{
23private:
24 vector<T> freeElements;
25 vector<T> usedElements;
26
27protected:
28 /**
29 * Instantiate element
30 */
31 virtual T instantiate() = 0;
32
33public:
34 /**
35 * Public constructor
36 */
37 Pool() {
38 }
39
40 virtual ~Pool() {
41 for (auto element: usedElements) {
42 delete element;
43 }
44 for (auto element: freeElements) {
45 delete element;
46 }
47 }
48
49 /**
50 * Allocate a new element from pool
51 * @return element
52 */
54 if (freeElements.empty() == false) {
55 T element = freeElements[freeElements.size() - 1];
56 freeElements.erase(freeElements.begin() + freeElements.size() - 1);
57 usedElements.push_back(element);
58 return element;
59 }
60 T element = instantiate();
61 usedElements.push_back(element);
62 return element;
63 }
64
65 /**
66 * Release element in pool for being reused
67 * @param element element
68 */
69 void release(T element) {
70 for (auto i = 0; i < usedElements.size(); i++) {
71 if (usedElements[i] == element) {
72 usedElements.erase(usedElements.begin() + i);
73 freeElements.push_back(element);
74 return;
75 }
76 }
77 }
78
79 /**
80 * @return element capacity
81 */
82 int32_t capacity() {
83 return usedElements.size() + freeElements.size();
84 }
85
86 /**
87 * @return elements in use
88 */
89 int32_t size() {
90 return usedElements.size();
91 }
92
93 /**
94 * Reset this pool
95 */
96 void reset() {
97 for (auto i = 0; i < usedElements.size(); i++) {
98 freeElements.push_back(usedElements[i]);
99 }
100 usedElements.clear();
101 }
102
103};
104
105};
106};
Pool template class.
Definition: Pool.h:22
virtual ~Pool()
Definition: Pool.h:40
int32_t capacity()
Definition: Pool.h:82
vector< T > usedElements
Definition: Pool.h:25
virtual T instantiate()=0
Instantiate element.
int32_t size()
Definition: Pool.h:89
T allocate()
Allocate a new element from pool.
Definition: Pool.h:53
void release(T element)
Release element in pool for being reused.
Definition: Pool.h:69
void reset()
Reset this pool.
Definition: Pool.h:96
vector< T > freeElements
Definition: Pool.h:24
Pool()
Public constructor.
Definition: Pool.h:37
Definition: fwd-tdme.h:4