Back out a5a5d2c176f7 (bug 882865) because of Android test failures on a CLOSED TREE
[gecko.git] / mfbt / RefPtr.h
blob3367e3ae437bd3fdad59d4be47bbe87dc93839d7
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 /* Helpers for defining and using refcounted objects. */
8 #ifndef mozilla_RefPtr_h_
9 #define mozilla_RefPtr_h_
11 #include "mozilla/Assertions.h"
12 #include "mozilla/Atomics.h"
13 #include "mozilla/Attributes.h"
14 #include "mozilla/TypeTraits.h"
16 namespace mozilla {
18 template<typename T> class RefCounted;
19 template<typename T> class RefPtr;
20 template<typename T> class TemporaryRef;
21 template<typename T> class OutParamRef;
22 template<typename T> OutParamRef<T> byRef(RefPtr<T>&);
24 /**
25 * RefCounted<T> is a sort of a "mixin" for a class T. RefCounted
26 * manages, well, refcounting for T, and because RefCounted is
27 * parameterized on T, RefCounted<T> can call T's destructor directly.
28 * This means T doesn't need to have a virtual dtor and so doesn't
29 * need a vtable.
31 * RefCounted<T> is created with refcount == 0. Newly-allocated
32 * RefCounted<T> must immediately be assigned to a RefPtr to make the
33 * refcount > 0. It's an error to allocate and free a bare
34 * RefCounted<T>, i.e. outside of the RefPtr machinery. Attempts to
35 * do so will abort DEBUG builds.
37 * Live RefCounted<T> have refcount > 0. The lifetime (refcounts) of
38 * live RefCounted<T> are controlled by RefPtr<T> and
39 * RefPtr<super/subclass of T>. Upon a transition from refcounted==1
40 * to 0, the RefCounted<T> "dies" and is destroyed. The "destroyed"
41 * state is represented in DEBUG builds by refcount==0xffffdead. This
42 * state distinguishes use-before-ref (refcount==0) from
43 * use-after-destroy (refcount==0xffffdead).
45 namespace detail {
46 #ifdef DEBUG
47 static const int DEAD = 0xffffdead;
48 #endif
50 // This is used WeakPtr.h as well as this file.
51 enum RefCountAtomicity
53 AtomicRefCount,
54 NonAtomicRefCount
57 template<typename T, RefCountAtomicity Atomicity>
58 class RefCounted
60 friend class RefPtr<T>;
62 protected:
63 RefCounted() : refCnt(0) { }
64 ~RefCounted() {
65 MOZ_ASSERT(refCnt == detail::DEAD);
68 public:
69 // Compatibility with nsRefPtr.
70 void AddRef() {
71 MOZ_ASSERT(refCnt >= 0);
72 ++refCnt;
75 void Release() {
76 MOZ_ASSERT(refCnt > 0);
77 if (0 == --refCnt) {
78 #ifdef DEBUG
79 refCnt = detail::DEAD;
80 #endif
81 delete static_cast<T*>(this);
85 // Compatibility with wtf::RefPtr.
86 void ref() { AddRef(); }
87 void deref() { Release(); }
88 int refCount() const { return refCnt; }
89 bool hasOneRef() const {
90 MOZ_ASSERT(refCnt > 0);
91 return refCnt == 1;
94 private:
95 typename Conditional<Atomicity == AtomicRefCount, Atomic<int>, int>::Type refCnt;
100 template<typename T>
101 class RefCounted : public detail::RefCounted<T, detail::NonAtomicRefCount>
103 public:
104 ~RefCounted() {
105 MOZ_STATIC_ASSERT((IsBaseOf<RefCounted, T>::value),
106 "T must derive from RefCounted<T>");
111 * AtomicRefCounted<T> is like RefCounted<T>, with an atomically updated
112 * reference counter.
114 template<typename T>
115 class AtomicRefCounted : public detail::RefCounted<T, detail::AtomicRefCount>
117 public:
118 ~AtomicRefCounted() {
119 MOZ_STATIC_ASSERT((IsBaseOf<AtomicRefCounted, T>::value),
120 "T must derive from AtomicRefCounted<T>");
125 * RefPtr points to a refcounted thing that has AddRef and Release
126 * methods to increase/decrease the refcount, respectively. After a
127 * RefPtr<T> is assigned a T*, the T* can be used through the RefPtr
128 * as if it were a T*.
130 * A RefPtr can forget its underlying T*, which results in the T*
131 * being wrapped in a temporary object until the T* is either
132 * re-adopted from or released by the temporary.
134 template<typename T>
135 class RefPtr
137 // To allow them to use unref()
138 friend class TemporaryRef<T>;
139 friend class OutParamRef<T>;
141 struct DontRef {};
143 public:
144 RefPtr() : ptr(0) { }
145 RefPtr(const RefPtr& o) : ptr(ref(o.ptr)) {}
146 RefPtr(const TemporaryRef<T>& o) : ptr(o.drop()) {}
147 RefPtr(T* t) : ptr(ref(t)) {}
149 template<typename U>
150 RefPtr(const RefPtr<U>& o) : ptr(ref(o.get())) {}
152 ~RefPtr() { unref(ptr); }
154 RefPtr& operator=(const RefPtr& o) {
155 assign(ref(o.ptr));
156 return *this;
158 RefPtr& operator=(const TemporaryRef<T>& o) {
159 assign(o.drop());
160 return *this;
162 RefPtr& operator=(T* t) {
163 assign(ref(t));
164 return *this;
167 template<typename U>
168 RefPtr& operator=(const RefPtr<U>& o) {
169 assign(ref(o.get()));
170 return *this;
173 TemporaryRef<T> forget() {
174 T* tmp = ptr;
175 ptr = 0;
176 return TemporaryRef<T>(tmp, DontRef());
179 T* get() const { return ptr; }
180 operator T*() const { return ptr; }
181 T* operator->() const { return ptr; }
182 T& operator*() const { return *ptr; }
183 template<typename U>
184 operator TemporaryRef<U>() { return TemporaryRef<U>(ptr); }
186 private:
187 void assign(T* t) {
188 unref(ptr);
189 ptr = t;
192 T* ptr;
194 static MOZ_ALWAYS_INLINE T* ref(T* t) {
195 if (t)
196 t->AddRef();
197 return t;
200 static MOZ_ALWAYS_INLINE void unref(T* t) {
201 if (t)
202 t->Release();
207 * TemporaryRef<T> represents an object that holds a temporary
208 * reference to a T. TemporaryRef objects can't be manually ref'd or
209 * unref'd (being temporaries, not lvalues), so can only relinquish
210 * references to other objects, or unref on destruction.
212 template<typename T>
213 class TemporaryRef
215 // To allow it to construct TemporaryRef from a bare T*
216 friend class RefPtr<T>;
218 typedef typename RefPtr<T>::DontRef DontRef;
220 public:
221 TemporaryRef(T* t) : ptr(RefPtr<T>::ref(t)) {}
222 TemporaryRef(const TemporaryRef& o) : ptr(o.drop()) {}
224 template<typename U>
225 TemporaryRef(const TemporaryRef<U>& o) : ptr(o.drop()) {}
227 ~TemporaryRef() { RefPtr<T>::unref(ptr); }
229 T* drop() const {
230 T* tmp = ptr;
231 ptr = 0;
232 return tmp;
235 private:
236 TemporaryRef(T* t, const DontRef&) : ptr(t) {}
238 mutable T* ptr;
240 TemporaryRef() MOZ_DELETE;
241 void operator=(const TemporaryRef&) MOZ_DELETE;
245 * OutParamRef is a wrapper that tracks a refcounted pointer passed as
246 * an outparam argument to a function. OutParamRef implements COM T**
247 * outparam semantics: this requires the callee to AddRef() the T*
248 * returned through the T** outparam on behalf of the caller. This
249 * means the caller (through OutParamRef) must Release() the old
250 * object contained in the tracked RefPtr. It's OK if the callee
251 * returns the same T* passed to it through the T** outparam, as long
252 * as the callee obeys the COM discipline.
254 * Prefer returning TemporaryRef<T> from functions over creating T**
255 * outparams and passing OutParamRef<T> to T**. Prefer RefPtr<T>*
256 * outparams over T** outparams.
258 template<typename T>
259 class OutParamRef
261 friend OutParamRef byRef<T>(RefPtr<T>&);
263 public:
264 ~OutParamRef() {
265 RefPtr<T>::unref(refPtr.ptr);
266 refPtr.ptr = tmp;
269 operator T**() { return &tmp; }
271 private:
272 OutParamRef(RefPtr<T>& p) : refPtr(p), tmp(p.get()) {}
274 RefPtr<T>& refPtr;
275 T* tmp;
277 OutParamRef() MOZ_DELETE;
278 OutParamRef& operator=(const OutParamRef&) MOZ_DELETE;
282 * byRef cooperates with OutParamRef to implement COM outparam semantics.
284 template<typename T>
285 OutParamRef<T>
286 byRef(RefPtr<T>& ptr)
288 return OutParamRef<T>(ptr);
291 } // namespace mozilla
293 #endif // mozilla_RefPtr_h_
296 #if 0
298 // Command line that builds these tests
300 // cp RefPtr.h test.cc && g++ -g -Wall -pedantic -DDEBUG -o test test.cc && ./test
302 using namespace mozilla;
304 struct Foo : public RefCounted<Foo>
306 Foo() : dead(false) { }
307 ~Foo() {
308 MOZ_ASSERT(!dead);
309 dead = true;
310 numDestroyed++;
313 bool dead;
314 static int numDestroyed;
316 int Foo::numDestroyed;
318 struct Bar : public Foo { };
320 TemporaryRef<Foo>
321 NewFoo()
323 return RefPtr<Foo>(new Foo());
326 TemporaryRef<Foo>
327 NewBar()
329 return new Bar();
332 void
333 GetNewFoo(Foo** f)
335 *f = new Bar();
336 // Kids, don't try this at home
337 (*f)->AddRef();
340 void
341 GetPassedFoo(Foo** f)
343 // Kids, don't try this at home
344 (*f)->AddRef();
347 void
348 GetNewFoo(RefPtr<Foo>* f)
350 *f = new Bar();
353 void
354 GetPassedFoo(RefPtr<Foo>* f)
357 TemporaryRef<Foo>
358 GetNullFoo()
360 return 0;
364 main(int argc, char** argv)
366 // This should blow up
367 // Foo* f = new Foo(); delete f;
369 MOZ_ASSERT(0 == Foo::numDestroyed);
371 RefPtr<Foo> f = new Foo();
372 MOZ_ASSERT(f->refCount() == 1);
374 MOZ_ASSERT(1 == Foo::numDestroyed);
377 RefPtr<Foo> f1 = NewFoo();
378 RefPtr<Foo> f2(NewFoo());
379 MOZ_ASSERT(1 == Foo::numDestroyed);
381 MOZ_ASSERT(3 == Foo::numDestroyed);
384 RefPtr<Foo> b = NewBar();
385 MOZ_ASSERT(3 == Foo::numDestroyed);
387 MOZ_ASSERT(4 == Foo::numDestroyed);
390 RefPtr<Foo> f1;
392 f1 = new Foo();
393 RefPtr<Foo> f2(f1);
394 RefPtr<Foo> f3 = f2;
395 MOZ_ASSERT(4 == Foo::numDestroyed);
397 MOZ_ASSERT(4 == Foo::numDestroyed);
399 MOZ_ASSERT(5 == Foo::numDestroyed);
402 RefPtr<Foo> f = new Foo();
403 f.forget();
404 MOZ_ASSERT(6 == Foo::numDestroyed);
408 RefPtr<Foo> f = new Foo();
409 GetNewFoo(byRef(f));
410 MOZ_ASSERT(7 == Foo::numDestroyed);
412 MOZ_ASSERT(8 == Foo::numDestroyed);
415 RefPtr<Foo> f = new Foo();
416 GetPassedFoo(byRef(f));
417 MOZ_ASSERT(8 == Foo::numDestroyed);
419 MOZ_ASSERT(9 == Foo::numDestroyed);
422 RefPtr<Foo> f = new Foo();
423 GetNewFoo(&f);
424 MOZ_ASSERT(10 == Foo::numDestroyed);
426 MOZ_ASSERT(11 == Foo::numDestroyed);
429 RefPtr<Foo> f = new Foo();
430 GetPassedFoo(&f);
431 MOZ_ASSERT(11 == Foo::numDestroyed);
433 MOZ_ASSERT(12 == Foo::numDestroyed);
436 RefPtr<Foo> f1 = new Bar();
438 MOZ_ASSERT(13 == Foo::numDestroyed);
441 RefPtr<Foo> f = GetNullFoo();
442 MOZ_ASSERT(13 == Foo::numDestroyed);
444 MOZ_ASSERT(13 == Foo::numDestroyed);
446 return 0;
449 #endif