]> Dogcows Code - chaz/yoink/blob - src/moof/manager.hh
pch support
[chaz/yoink] / src / moof / manager.hh
1
2 /*] Copyright (c) 2009-2011, Charles McGarvey [*****************************
3 **] All rights reserved.
4 *
5 * Distributable under the terms and conditions of the 2-clause BSD license;
6 * see the file COPYING for a complete text of the license.
7 *
8 *****************************************************************************/
9
10 #ifndef _MOOF_MANAGER_HH_
11 #define _MOOF_MANAGER_HH_
12
13 #include <string>
14 #include <boost/shared_ptr.hpp>
15
16 #include <moof/hash.hh>
17
18
19 /**
20 * \file manager.hh
21 * A manager is a collection of named objects of the same type. Libraries
22 * use reference counting to automagically delete objects which no longer
23 * have any interested code.
24 */
25
26 namespace moof {
27
28
29 template <class T>
30 class manager
31 {
32 public:
33
34 manager() :
35 retain_count_(1) {}
36
37 const std::string& name() const
38 {
39 return name_;
40 }
41
42 static boost::shared_ptr<T> instance(const std::string& name)
43 {
44 return boost::shared_ptr<T>(retain(name), &release);
45 }
46
47 private:
48
49 typedef stlplus::hash<std::string,T*,hash_function> ptr_lookup;
50
51 static T* retain(const std::string& name)
52 {
53 typename ptr_lookup::iterator it = ptr_lookup_.find(name);
54
55 if (it != ptr_lookup_.end())
56 {
57 ++((*it).second->retain_count_);
58 return (*it).second;
59 }
60 else
61 {
62 T* new_object(new T);
63 if (new_object)
64 {
65 new_object->name_ = name;
66 new_object->init(name);
67 ptr_lookup_.insert(std::make_pair(name,
68 new_object));
69 }
70 return new_object;
71 }
72 }
73
74 static void release(T* obj)
75 {
76 if (--(obj->retain_count_) == 0)
77 {
78 ptr_lookup_.erase(obj->name_);
79 delete obj;
80 }
81 }
82
83
84 static ptr_lookup ptr_lookup_;
85 std::string name_;
86 unsigned retain_count_;
87 };
88
89 template <class T>
90 hash<std::string,T*,hash_function> manager<T>::ptr_lookup_;
91
92
93 } // namespace moof
94
95 #endif // _MOOF_MANAGER_HH_
96
This page took 0.039192 seconds and 5 git commands to generate.