* after the last interested code releases its hold on the object.
*/
-#include <map>
#include <string>
+#include <boost/shared_ptr.hpp>
+
+#include <Moof/Hash.hh>
+
namespace Mf {
template <class T>
class Mippleton
{
- typedef std::pair<unsigned,T*> ptr_value_t;
- typedef std::pair<std::string,ptr_value_t> ptr_map_pair_t;
- typedef std::map<std::string,ptr_value_t> ptr_map_t;
+ typedef std::pair<unsigned,T*> PtrValue;
+ typedef stlplus::hash<std::string,PtrValue,getHash> PtrMap;
- static ptr_map_t ptrs_;
- std::string name_;
+ static PtrMap ptrs_;
+ std::string name_;
-public:
- explicit Mippleton(const std::string& name) : name_(name) {}
-
- inline const std::string& getName() const
+ static T* retain(const std::string& name)
{
- return name_;
- }
-
- inline static T* retain(const std::string& name)
- {
- typename ptr_map_t::iterator it;
+ typename PtrMap::iterator it = ptrs_.find(name);
- if ((it = ptrs_.find(name)) != ptrs_.end())
+ if (it != ptrs_.end())
{
- (*it).second.first++;
+ ++((*it).second.first);
return (*it).second.second;
}
else
{
T* newObj = new T(name);
- ptrs_.insert(ptr_map_pair_t(name, ptr_value_t(1, newObj)));
+ ptrs_.insert(std::make_pair(name, std::make_pair(1, newObj)));
return newObj;
}
}
- inline static void releaseByName(const std::string& name)
+ static void release(T* obj)
+ {
+ releaseByName(obj->name_);
+ }
+
+ static void releaseByName(const std::string& name)
{
- typename ptr_map_t::iterator it;
+ typename PtrMap::iterator it;
- if ((it = ptrs_.find(name)) != ptrs_.end() && -(*it).second.first == 0)
+ if ((it = ptrs_.find(name)) != ptrs_.end() && --(*it).second.first == 0)
{
delete (*it).second.second;
- ptrs_.erase(it);
+ ptrs_.erase((*it).first);
}
}
- inline static void release(T* obj)
+public:
+
+ explicit Mippleton(const std::string& name) :
+ name_(name) {}
+
+ const std::string& getName() const
+ {
+ return name_;
+ }
+
+ static boost::shared_ptr<T> getInstance(const std::string& name)
{
- releaseByName(obj->getName());
+ return boost::shared_ptr<T>(retain(name), &release);
}
};
template <class T>
-std::map<std::string,std::pair<unsigned,T*> > Mippleton<T>::ptrs_;
+stlplus::hash< std::string,std::pair<unsigned,T*>,getHash >
+ Mippleton<T>::ptrs_;
} // namespace Mf