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