ObjectCache.h
Go to the documentation of this file.
/* Frobby: Software for monomial ideal computations.
Copyright (C) 2009 University of Aarhus
Contact Bjarke Hammersholt Roune for license information (www.broune.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/.
*/
#ifndef OBJECT_CACHE_GUARD
#define OBJECT_CACHE_GUARD
#include "ElementDeleter.h"
#include <vector>
template<class T>
class ObjectCache {
public:
ObjectCache();
unique_ptr<T> newObject();
template<class S>
unique_ptr<T> newObjectCopy(const S& copyOf);
template<class S>
void freeObject(unique_ptr<S> object);
private:
vector<T*> _cache;
ElementDeleter<vector<T*> > _cacheDeleter;
};
// The implementation has to be inline because we are using templates.
template<class T>
inline ObjectCache<T>::ObjectCache():
_cache(),
_cacheDeleter(_cache) {
}
template<class T>
unique_ptr<T> ObjectCache<T>::newObject() {
if (_cache.empty())
return unique_ptr<T>(new T());
unique_ptr<T> object(_cache.back());
_cache.pop_back();
return object;
}
template<class T> template<class S>
unique_ptr<T> ObjectCache<T>::newObjectCopy(const S& copyOf) {
if (_cache.empty())
return unique_ptr<T>(new T(copyOf));
unique_ptr<T> object(_cache.back());
_cache.pop_back();
*object = copyOf;
return object;
}
template<class T> template<class S>
void ObjectCache<T>::freeObject(unique_ptr<S> object) {
ASSERT(dynamic_cast<T*>(object.get()) != 0);
unique_ptr<T> casted(static_cast<T*>(object.release()));
noThrowPushBack(_cache, std::move(casted));
}
#endif
ElementDeleter.h
noThrowPushBack
void noThrowPushBack(Container &container, unique_ptr< Element > pointer)
Definition ElementDeleter.h:141
ElementDeleter
Definition ElementDeleter.h:50
ObjectCache::newObjectCopy
unique_ptr< T > newObjectCopy(const S &copyOf)
Returns a copy of copyOf.
Definition ObjectCache.h:79
ObjectCache::_cache
vector< T * > _cache
Definition ObjectCache.h:56
ObjectCache::ObjectCache
ObjectCache()
Definition ObjectCache.h:63
ObjectCache::newObject
unique_ptr< T > newObject()
Returns an object.
Definition ObjectCache.h:69
ObjectCache::freeObject
void freeObject(unique_ptr< S > object)
Insert an object into the cache.
Definition ObjectCache.h:90
ObjectCache::_cacheDeleter
ElementDeleter< vector< T * > > _cacheDeleter
Definition ObjectCache.h:57
ASSERT
#define ASSERT(X)
Definition stdinc.h:86