Click
Loading...
Searching...
No Matches
memorypool.hh
1#ifndef MIDDLEBOX_MEMORYPOOL_HH
2#define MIDDLEBOX_MEMORYPOOL_HH
3
4/*
5 * memorypool.hh - Template for a memory pool
6 *
7 * Romain Gaillard.
8 */
9
18template <typename T>
20{
21 int const DEFAULT_ALLOC = 1024;
22public:
26 {
27 first = NULL;
28 }
29
33 MemoryPool(unsigned int initialSize)
34 {
35 first = NULL;
36
37 // Perform the first allocation. 'initialSize' memory chunks will be
38 // allocated
39 initialize(initialSize);
40 }
41
45 {
46 MemoryPoolNode *node = first;
47 MemoryPoolNode *toDelete = NULL;
48
49 // Free each node of the list
50 while(node != NULL)
51 {
52 toDelete = node;
53 node = node->next;
54
55 // Free the node
56 delete toDelete;
57 }
58 }
59
63 void initialize(unsigned int initialSize)
64 {
65 if(first != NULL)
66 return;
67
68 // Perform the first allocation. 'initialSize' memory chunks will be
69 // allocated
70 allocateMoreMemory(initialSize);
71 }
72
77 {
78 MemoryPoolNode *node = first;
79
80 if(first == NULL)
81 {
82 allocateMoreMemory(DEFAULT_ALLOC);
83 node = first;
84 }
85
86 first = node->next;
87
88 return (T*)node;
89 }
90
94 void releaseMemory(T* p)
95 {
96 ((MemoryPoolNode*)p)->next = first;
97 first = (MemoryPoolNode*)p;
98 }
99
100private:
101 // Element of the pool
102 union MemoryPoolNode
103 {
104 MemoryPoolNode *next;
105 T data;
107 // Constructors and destructors required since T can be an object with a constructor
108 // that will be deleted from the union (C++11)
109 MemoryPoolNode()
110 {
111 next = NULL;
112 }
113
114 ~MemoryPoolNode()
115 {
116
117 }
118 };
119
123 void allocateMoreMemory(unsigned int size)
124 {
125 MemoryPoolNode *node = NULL;
126 // Creating 'initialSize' elements;
127 for(unsigned i = 0; i < size; ++i)
128 {
129 // Allocate the node
130 node = new MemoryPoolNode;
131
132 node->next = first;
133 first = node;
134 }
135 }
136
137 MemoryPoolNode* first;
139};
140
141#endif
Template for memory pools.
Definition memorypool.hh:20
MemoryPool()
Construct an empty MemoryPool.
Definition memorypool.hh:25
void releaseMemory(T *p)
Release memory and put it back in the pool.
Definition memorypool.hh:94
~MemoryPool()
Destruct the memory pool.
Definition memorypool.hh:44
MemoryPool(unsigned int initialSize)
Construct a MemoryPool.
Definition memorypool.hh:33
T * getMemory()
Obtain memory from the memory pool.
Definition memorypool.hh:76
void initialize(unsigned int initialSize)
Initialize the MemoryPool.
Definition memorypool.hh:63