|
libGDF
|
00001 // 00002 // This file is part of libGDF. 00003 // 00004 // libGDF is free software: you can redistribute it and/or modify 00005 // it under the terms of the GNU Lesser General Public License as 00006 // published by the Free Software Foundation, either version 3 of 00007 // the License, or (at your option) any later version. 00008 // 00009 // libGDF is distributed in the hope that it will be useful, 00010 // but WITHOUT ANY WARRANTY; without even the implied warranty of 00011 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 00012 // GNU Lesser General Public License for more details. 00013 // 00014 // You should have received a copy of the GNU Lesser General Public License 00015 // along with libGDF. If not, see <http://www.gnu.org/licenses/>. 00016 // 00017 // Copyright 2010 Martin Billinger 00018 00019 #ifndef POINTERPOOL_H 00020 #define POINTERPOOL_H 00021 00022 #include <list> 00023 #include <iostream> 00024 00025 template<typename T> 00026 class PointerPool 00027 { 00028 public: 00030 PointerPool( T type_template, size_t num_el = 1000 ) 00031 { 00032 if( num_el == 0 ) 00033 throw std::invalid_argument( "PointerPool must not be empty." ); 00034 m_size_increment = num_el; 00035 00036 m_avail = num_el; 00037 00038 m_instances.resize( num_el, type_template ); 00039 00040 typename std::list<T>::iterator it = m_instances.begin( ); 00041 for( ; it != m_instances.end(); it++ ) 00042 m_free_pointers.push_back( &(*it) ); 00043 00044 std::cout << "PointerPool::PointerPool( )" << std::endl; 00045 } 00046 00048 virtual ~PointerPool( ) 00049 { 00050 std::cout << "PointerPool::~PointerPool( )" << std::endl; 00051 } 00052 00054 void expand( size_t num_el ) 00055 { 00056 std::cout << "PointerPool::expand( )" << std::endl; 00057 for( size_t i=0; i<num_el; i++ ) 00058 { 00059 m_instances.push_back( m_instances.front( ) ); // insert copies of the first element 00060 m_free_pointers.push_back( &m_instances.back() ); 00061 } 00062 m_avail += num_el; 00063 } 00064 00066 T* pop( ) 00067 { 00068 if( m_avail == 0 ) 00069 expand( m_size_increment ); 00070 00071 T* ptr = m_free_pointers.front( ); 00072 m_free_pointers.pop_front( ); 00073 m_avail--; 00074 return ptr; 00075 } 00076 00078 /*T* pop( const T &src ) 00079 { 00080 if( m_avail == 0 ) 00081 expand( m_size_increment ); 00082 00083 T* ptr = m_free_pointers.front( ); 00084 m_free_pointers.pop_front( ); 00085 m_avail--; 00086 00087 *ptr = src; 00088 00089 return ptr; 00090 }*/ 00091 00092 void push( T* ptr ) 00093 { 00094 m_free_pointers.push_back( ptr ); 00095 m_avail++; 00096 } 00097 00098 private: 00099 size_t m_size_increment; 00100 size_t m_avail; 00101 00102 std::list<T> m_instances; 00103 std::list<T*> m_free_pointers; 00104 }; 00105 00106 #endif // POINTERPOOL_H