/** * @file include/ActivMiddleware/Misc/SharedObjectCache.h * * @brief Shared object cache template. */ #if (!defined ACTIV_MIDDLEWARE_MISC_SHARED_OBJECT_CACHE_H) #define ACTIV_MIDDLEWARE_MISC_SHARED_OBJECT_CACHE_H #include "ActivMiddleware/Misc/StlHelper.h" #include ACTIV_BOOST_INCLUDE(smart_ptr/intrusive_ptr.hpp) #include ACTIV_BOOST_INCLUDE(smart_ptr/intrusive_ref_counter.hpp) #include //! Activ namespace. namespace Activ { /** * @brief Helper class to order a container of pointers by the pointed-to value rather than virtual address. */ template class SharedObjectPointerOrder { public: bool operator()(const T * const pLhs, const T * const pRhs) const { return (*pLhs < *pRhs); } }; // --------------------------------------------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------------------------------------------- /** * @brief Cache of objects that can be shared. * * T the type of object to cache. Must be copy-constructible. * ORDER ordering for the underlying set of T*. */ template > class SharedObjectCache { public: /** * @brief The cached object. Essentially just T with the addition of a reference count. */ class CachedObject : public T, public Boost::intrusive_ref_counter { public: /** * @brief Destructor. Invoked when all instrusive pointer references to this value are released, * and causes the value to be removed from the cache. */ ~CachedObject() { m_sharedObjectCache.m_cache.erase(this); } private: /** * @brief Constructor. * * @param sharedObjectCache the cache this object is going to be a member of. * @param value */ CachedObject(SharedObjectCache &sharedObjectCache, const T &value) : T(value), m_sharedObjectCache(sharedObjectCache) { } SharedObjectCache &m_sharedObjectCache; friend class SharedObjectCache; }; typedef Boost::intrusive_ptr Pointer; /** * @brief Get an object from the cache. * * @param value the value to get from the cache, or new value to be added. * * @return Intrusive const-pointer to the value. When all intrusive pointers to the value have been destroyed, * the value is removed from the cache. */ const Pointer Get(const T &value) { const CachedObject *pCachedObject; Cache::iterator iter; // Lookup an existing member of the cache with value "value", or find where we can insert it. if (SetFind(m_cache, &value, iter)) { // Value is in the cache. We know it must be a CachedObject since we created it, so cast is OK. pCachedObject = static_cast(*iter); } else { // Create a new value and insert in to the cache. pCachedObject = new CachedObject(*this, value); iter = m_cache.insert(iter, pCachedObject); } return Pointer(pCachedObject); } private: typedef std::set Cache; Cache m_cache; }; } // namespace Activ #endif // (!defined ACTIV_MIDDLEWARE_MISC_SHARED_OBJECT_CACHE_H)