#endif
#include "GraphicsCache.h"
+#include "GraphicsCacheItem.h"
#include "support/LAssert.h"
-GraphicsCache * GraphicsCache::singleton = 0;
-
-
-GraphicsCache *
+GraphicsCache &
GraphicsCache::getInstance()
{
- if (! singleton) {
- singleton = new GraphicsCache;
- Assert(singleton != 0);
- }
-
- return singleton;
+ static GraphicsCache singleton;
+ return singleton;
}
GraphicsCache::~GraphicsCache()
{
- // Free the map.
- //std::foreach(map.begin(), map.end(), ...);
- // This is not really needed, it will only happen on program close and in
- // any case the OS will release those resources (not doing it may have
- // a good effect on closing time).
-
- delete singleton;
+ // All elements are destroyed by the shared_ptr's in the map.
}
-GraphicsCacheItem *
+GraphicsCache::shared_ptr_item
GraphicsCache::addFile(string const & filename)
{
- CacheType::const_iterator it = cache.find(filename);
-
- if (it != cache.end()) {
- return (*it).second;
- }
+ CacheType::iterator it = cache.find(filename);
- GraphicsCacheItem * cacheItem = new GraphicsCacheItem();
- if (cacheItem == 0) {
- return 0;
+ if (it != cache.end()) {
+ return it->second;
}
-
- bool result = cacheItem->setFilename(filename);
- if (!result)
- return 0;
-
- cache[filename] = cacheItem;
- return cacheItem;
+ shared_ptr_item cacheItem(new GraphicsCacheItem(filename));
+ if (cacheItem.get() == 0)
+ return cacheItem;
+
+ cache[filename] = cacheItem;
+
+ // GraphicsCacheItem_ptr is a shared_ptr and thus reference counted,
+ // it is safe to return it directly.
+ return cacheItem;
}
void
GraphicsCache::removeFile(string const & filename)
{
- CacheType::const_iterator it = cache.find(filename);
-
- if (it != cache.end()) {
- // INCOMPLETE!
-// cache.erase(it);
- }
+ // We do not destroy the GraphicsCacheItem since we are here because
+ // the last copy of it is being erased.
+
+ CacheType::iterator it = cache.find(filename);
+ if (it != cache.end())
+ cache.erase(it);
}