Frobby  0.9.5
ObjectCache.h
Go to the documentation of this file.
1 /* Frobby: Software for monomial ideal computations.
2  Copyright (C) 2009 University of Aarhus
3  Contact Bjarke Hammersholt Roune for license information (www.broune.com)
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9 
10  This program is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  GNU General Public License for more details.
14 
15  You should have received a copy of the GNU General Public License
16  along with this program. If not, see http://www.gnu.org/licenses/.
17 */
18 #ifndef OBJECT_CACHE_GUARD
19 #define OBJECT_CACHE_GUARD
20 
21 #include "ElementDeleter.h"
22 
23 #include <vector>
24 
34 template<class T>
35 class ObjectCache {
36  public:
38 
42  auto_ptr<T> newObject();
43 
48  template<class S>
49  auto_ptr<T> newObjectCopy(const S& copyOf);
50 
52  template<class S>
53  void freeObject(auto_ptr<S> object);
54 
55  private:
56  vector<T*> _cache;
58 };
59 
60 // The implementation has to be inline because we are using templates.
61 
62 template<class T>
64  _cache(),
65  _cacheDeleter(_cache) {
66 }
67 
68 template<class T>
70  if (_cache.empty())
71  return auto_ptr<T>(new T());
72 
73  auto_ptr<T> object(_cache.back());
74  _cache.pop_back();
75  return object;
76 }
77 
78 template<class T> template<class S>
79 auto_ptr<T> ObjectCache<T>::newObjectCopy(const S& copyOf) {
80  if (_cache.empty())
81  return auto_ptr<T>(new T(copyOf));
82 
83  auto_ptr<T> object(_cache.back());
84  _cache.pop_back();
85  *object = copyOf;
86  return object;
87 }
88 
89 template<class T> template<class S>
90 void ObjectCache<T>::freeObject(auto_ptr<S> object) {
91  ASSERT(dynamic_cast<T*>(object.get()) != 0);
92 
93  auto_ptr<T> casted(static_cast<T*>(object.release()));
94  noThrowPushBack(_cache, casted);
95 }
96 
97 #endif
void noThrowPushBack(Container &container, auto_ptr< Element > pointer)
An ObjectCache keeps a cache of previously-used objects to cut down on the number of allocations.
Definition: ObjectCache.h:35
auto_ptr< T > newObjectCopy(const S &copyOf)
Returns a copy of copyOf.
Definition: ObjectCache.h:79
auto_ptr< T > newObject()
Returns an object.
Definition: ObjectCache.h:69
vector< T * > _cache
Definition: ObjectCache.h:56
void freeObject(auto_ptr< S > object)
Insert an object into the cache.
Definition: ObjectCache.h:90
ElementDeleter< vector< T * > > _cacheDeleter
Definition: ObjectCache.h:57
#define ASSERT(X)
Definition: stdinc.h:86