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