Ilwis-Objects  1.0
GIS and Remote Sensing framework for data access and processing
All Classes Functions Enumerations Pages
memorymanager.h
1 template<class T> class MemoryManager {
2  struct MemoryPool {
3  T * _pool;
4  vector<unsigned long> _freeList;
5 
6  };
7 public:
8  MemoryManager(unsigned long initSize=10000) : size(initSize){
9  createNewPool();
10  }
11 
12  ~MemoryManager() {
13  for(int i = 0; i < _pools.size(); ++i) {
14  delete [] _pools[i]._pool;
15  }
16  }
17 
18  T* allocate() {
19  if ( _pools[current]._freeList.size() == 0) {
20  int i=0;
21  // try to find a pool that has space
22  for( ; i < _pools.size(); ++i) {
23  if( _pools[i]._freeList.size() > 0) {
24  current = i;
25  break;
26  }
27  }
28  if ( i == _pools.size()) // no pools to be found
29  createNewPool();
30  }
31  unsigned long index = _pools[current]._freeList.back();
32  _pools[current]._freeList.pop_back();
33  return &_pools[current]._pool[index];
34  }
35 
36  // frees the index of the used pointer,
37  void deallocate(T* object) {
38  unsigned long ptr = (unsigned long)object;
39  for(int i=0 ; i < _pools.size(); ++i) {
40  unsigned long begin = (unsigned long)_pools[i]._pool;
41  unsigned long end = begin + sizeof(T)*size;
42  if ( ptr >= begin && ptr <= end) {
43  unsigned long index = (end - ptr) / sizeof(T);
44  current = i;
45  if ( index > 0){
46  _pools[current]._freeList.push_back(size - index);
47  break;
48  }
49  }
50  }
51  }
52 
53 private:
54  void createNewPool() {
55  list<unsigned long> newList;
56  MemoryPool p;
57  p._pool = new T[size];
58  _pools.push_back(p);
59  current = _pools.size() - 1;
60  _pools[current]._freeList.resize(size);
61  for(unsigned long index = 0; index< size; ++index)
62  _pools[current]._freeList[index] = index;
63 
64 
65 
66  }
67  vector<MemoryPool> _pools;
68  int current;
69  unsigned long size;
70 
71 };