Debian Codegraph @

README.SMART-POINTERS

raw
1 Smart pointers in aptitude
2
3
4 IMPORTANT NOTE:
5
6 All (or most of) the smart pointers documented here are deprecated
7 in favor of boost::shared_ptr, which is simpler, more flexible, and
8 probably more efficient (although I haven't checked that). New code
9 should use shared_ptr and/or scoped_ptr.
10
11 NEW STUFF:
12
13 The preferred convention for new code is to use boost's shared_ptr
14 and scoped_ptr classes. If you just have a private pointer that
15 should never be "owned" by other code, you might consider scoped_ptr.
16 Otherwise, shared_ptr is a better bet. You should think twice before
17 writing bare pointers.
18
19 shared_ptr is NOT MAGIC. You can still get memory leaks and crashes
20 if you misuse it; it is merely a tool to help you manage your object
21 lifetimes. The following notes will help.
22
23 * Do not write this code:
24
25 boost::shared_ptr<T> t = new T(...);
26
27 It is (potentially) exception-unsafe. Instead of thinking hard
28 about whether it's safe or not, do this, which is both safe and
29 more efficient:
30
31 boost::shared_ptr<T> t = boost::make_shared<T>(...);
32
33 * Be very careful about creating circular chains of shared_ptrs.
34 These cannot be reclaimed by the shared_ptr mechanism and will
35 result in memory leaks. Many of the notes below are just
36 ways of avoiding this.
37
38 * Although shared_ptr technically allows "sharing" of pointers, most
39 shared_ptr objects in aptitude should have a single owner at any
40 given time, just like bare pointers. For instance, look at how
41 search patterns are normally handled. pattern::create() might be
42 invoked from some subroutine. It creates a pattern in a
43 shared_ptr and returns it, passing ownership to its caller. Its
44 caller in turn invokes the constructor of another object, passing
45 the pattern's shared_ptr in. The constructor takes ownership and
46 stores the pattern in a member variable for later use.
47
48 The difference between shared_ptr and bare pointers is that
49 violating the above pattern will at worst produce a memory leak
50 rather than a crash.
51
52 * For "leaf" objects that don't store smart pointers to anything
53 else, using shared_ptr to freely share references is reasonable.
54
55 * Objects that form an acyclic graph can be safely
56 reference-counted. You can force the objects in a module to form
57 an acyclic graph by making their constructor(s) take pointers to
58 other objects, and by not providing a way to modify links after
59 the fact. For instance, the match pattern objects and the (not
60 shared) fragment objects use this approach. Be sure that you
61 don't have strong references to objects outside the module,
62 though, or you can still be bitten by this problem.
63
64 * Be very careful about embedding shared_ptrs into callbacks. If
65 the type you're embedding can't contain strong references, this is
66 OK. If it can, you can end up creating a hidden reference cycle
67 that will be hard to debug. Consider using boost's weak_ptr
68 object, which automatically becomes invalid when its parent
69 shared_ptr is destroyed.
70
71 Callbacks passed to the main loop are a special case, since those
72 are normally not stored permanently anywhere (i.e., they have no
73 strong incoming references), and there may be lifetime issues that
74 make weak references unacceptable. If you rely on this, be sure
75 to document it in comments and ensure that you really don't take a
76 strong reference to the callback. It's better not to do this, but
77 I know there were a few places that I ran into where it was handy.
78
79 * Because there is a cost to using shared_ptr, don't use it
80 willy-nilly, particularly for low-level code.
81
82 OLD DEPRECATED STUFF:
83
84 aptitude uses smart pointers in a number of ways internally. These
85 techniques generally simplify the code and make it easy to program
86 safely, but C++ being what it is, you should be aware of how they work
87 and what the caveats are.
88
89 * threading
90
91 As of this writing, none of the smart pointers lock their reference
92 counts (implementing locks in the imm::wtree class caused the
93 problem resolver's running time to increase by 50%!). Some of the
94 less-commonly-used ones may get locking in the future, but for the
95 time being you should handle objects that are given to another
96 thread carefully -- do deep copies of anything that's
97 reference-counted. (this is only the imm::* stuff at the moment, so
98 the problem is managable) For more information on threading, see
99 README.THREADS.
100
101 * reference-counted immutable values
102
103 aptitude employs reference-counting of immutable objects in several
104 places. For the most part this is invisible to clients; the typical
105 implementation looks like this:
106
107 class foo
108 {
109 class foo_impl
110 {
111 ...
112 public:
113 void m1();
114 void m2(int);
115 ...
116 };
117 public:
118 void m1();
119 void m2(int);
120 ...
121 };
122
123 When you create a new "foo" object, a corresponding foo_impl is
124 created with reference-count 1. Reference counts are managed
125 in all the ways you expect, and the object is deleted when you're
126 done with it.
127
128 This use of reference-counting can be viewed as a performance hack:
129 since the objects are immutable, pass-by-value is indistinguishable
130 from pass-by-reference; if we can prove that no strong cycles will
131 be created, it's always safe to reference-count objects like this.
132
133
134 * auto_ptr for temporary return values
135
136 When building up a temporary return value, several routines use
137 auto_ptrs to store intermediates:
138
139 auto_ptr<T> v1 = parse_T_from_string(str1);
140 auto_ptr<T> v2 = parse_T_from_string(str2);
141
142 The advantage here is that you can freely throw exceptions and/or
143 break out of the function with an early "return" without worrying
144 about which of {v1,v2} have to be deleted. To actually return them,
145 you'd do something like this:
146
147 return pair<T*,T*>(v1.release(), v2.release());
148
149 The "release" calls tell v1 and v2 that they no longer "own" their
150 respective pointers.
151
152
153
154 * reference-counting of display widgets
155
156 Display widgets are also reference-counted. This is a
157 generalization of the idea that "the enclosing widget owns this
158 one"; it provides more support for extending the lifetime of a
159 widget if, for instance, you want to extract values from it after
160 its parent is done with it. Unfortunately, this reference counting
161 is NOT fully transparent, and you should be aware of some basic
162 principles:
163
164 - As with any reference counting scheme, it is up to you to
165 avoid creating strong cycles. By default, the only
166 non-transient strong references are references from a parent to
167 a child; your best bet is to ensure that all additional strong
168 references either have stack lifetime or do not close cycles.
169
170 If you must create a cycle, make sure it gets explicitly broken
171 before all external references to it are lost.
172
173 - Reference-counting is done via the generic ref_ptr class
174 (ref_ptr.h). This is a templated class, like auto_ptr, and
175 generally works as you expect. To enforce the use of ref_ptr,
176 all widget constructors are protected; static ::create methods
177 are provided to actually allocate a new widget. Because the
178 cwidget::widget class initializes its reference count to 1, the
179 ::create method should explicitly decref() its return value; see
180 the existing ::create routines for examples.
181
182 To make code a bit more readable, adopt the convention of
183 creating typedefs for ref_ptr wrappers around new classes. For
184 instance, if you have just created the class vs_moo, add the
185 following line to its header file:
186
187 typedef ref_ptr<vs_moo> vs_moo_ref;
188
189 - Watch out for deletion of "this". If you aren't sure whether
190 "this" will be deleted in a method, I recommend creating a
191 method-scoped strong reference to it:
192
193 ref_ptr<this_type> thisref = this;
194
195 Doing so will prevent "this" from being deleted until the
196 current method terminates and is probably good practice in
197 general.
198
199 - Beware sigc::bind. sigc::bind is an easy way to create bad
200 circularities; moreover, it's actually unsafe to bind a ref_ptr
201 as a slot argument. The solution adopted in cwidget is to
202 exploit sigc++ weak references. If w is a ref_ptr, then rather
203 than closing w, you should close over w.weak_ref().
204
205 Unfortunately, w.weak_ref() will appear to the callee as a C++
206 reference, not a ref_ptr: if w has type T, you need a slot that
207 accepts a T&, not a ref_ptr<T>. To solve this problem, it is
208 conventional for widgets defining public interfaces that accept
209 a ref_ptr<T> to define a corresponding _bare method that accepts
210 a T&; the _bare method should simply instantiate a ref_ptr and
211 call the main interface. For instance,
212
213 void add_widget(const ref_ptr<cwidget::widget> &w);
214 void add_widget_bare(cwidget::widget &w)
215 {
216 add_widget(ref_ptr<cwidget::widget>(&w));
217 }
218
219 Obviously this is less than ideal, but it will work. Be aware,
220 though, that the bound argument is a *weak* reference: if there
221 are no strong references to a bound widget, the signal
222 connection will simply disappear.