// ClassPool implementation #include "classpool.h" #include <stdlib.h> // for malloc, free #include <iostream> using std::cout; using std::cerr; using std::endl; #include <exception> // for std::bad_alloc using std::bad_alloc; // Globals bool ClassPool::empty = true; int ClassPool::next = 0; void* ClassPool::pool[MAX_MEMORY]; ClassPool::ClassPool() { cout << "Constructing an object" << endl; } ClassPool::~ClassPool() { cout << "Destroying an object" << endl; } // ClassPool's default constructor implicitly called here void* ClassPool::operator new (size_t size) { cout << "Allocate memory size to pool: " << size << endl; void *p = allocate_from_pool(size); return p; } // ClassPool's destructor implicitly called at this point void ClassPool::operator delete (void *p) { // return memory to pool cout << "return memory to pool: " << p << endl; release(p); } void* ClassPool::allocate_from_pool(size_t size) { if ( empty ) { empty = false; cout << "Allocating memory for " << MAX_MEMORY << " items." << endl; for (int i=0; i < MAX_MEMORY; i++) pool[i] = malloc(size); for (int i=0; i < MAX_MEMORY; i++) cout << i << ": " << pool[i] << endl; } if ( next >= MAX_MEMORY ) { cerr << "Out of memory!" << endl; throw std::bad_alloc(); // ANSI/ISO compliant behavior // exit(12); // Can not allocate memory on Red Had linux } next++; return pool[next-1]; } void ClassPool::release (void *p) { int index = 0; void* ptr; cout << "releasing this memory: " << p << endl; // shuffle memory references till the free memory is at the end while ( index < MAX_MEMORY && p != pool[index] ) { cout << index << " : " << pool[index] << endl; ++index; } if ( index == MAX_MEMORY ) { // found nothing? cout << "No memory match in pool" << endl; return; } else if ( next == 0 ) { // allocated nothing? cout << "No memory in pool" << endl; return; } cout << "Memory pointer found in index: " << index<< endl; cout << "Current pointer: " << next << endl; ptr = pool[index]; next--; pool[index] = pool[next]; pool[next] = ptr; cout << "New pointer: " << next << endl; cout << "Memory restored to pool: " << ptr << endl; } void ClassPool::release_all() { empty = true; cout << "Releasing " << MAX_MEMORY << " items in class memory pool" << endl; for (int i=0; i < MAX_MEMORY; i++) cout << i << ": " << pool[i] << endl; for (int i = 0; i < MAX_MEMORY; ++i) free(pool[i]), pool[i] = NULL; next = 0; }
Hosted by www.Geocities.ws

1