/*] Copyright (c) 2009-2010, Charles McGarvey [************************** **] All rights reserved. * * vi:ts=4 sw=4 tw=75 * * Distributable under the terms and conditions of the 2-clause BSD license; * see the file COPYING for a complete text of the license. * **************************************************************************/ #ifndef _MOOF_MANAGER_HH_ #define _MOOF_MANAGER_HH_ /** * @file Manager.hh * A library is a collection of named objects of the same type. Libraries * use reference counting to automagically delete objects which no longer * have any interested code. */ #include #include #include namespace Mf { template class Manager { public: Manager() : mRetainCount(1) {} const std::string& getName() const { return mName; } static boost::shared_ptr getInstance(const std::string& name) { return boost::shared_ptr(retain(name), &release); } private: typedef stlplus::hash PtrMap; static PtrMap mPtrMap; std::string mName; unsigned mRetainCount; static T* retain(const std::string& name) { typename PtrMap::iterator it = mPtrMap.find(name); if (it != mPtrMap.end()) { ++((*it).second->mRetainCount); return (*it).second; } else { T* newObj(new T); if (newObj) { newObj->mName = name; newObj->init(name); mPtrMap.insert(std::make_pair(name, newObj)); } return newObj; } } static void release(T* obj) { if (--(obj->mRetainCount) == 0) { mPtrMap.erase(obj->mName); delete obj; } } }; template stlplus::hash Manager::mPtrMap; } // namespace Mf #endif // _MOOF_MANAGER_HH_