1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /* Helpers for defining and using refcounted objects. */
9 #ifndef mozilla_RefPtr_h
10 #define mozilla_RefPtr_h
12 #include "mozilla/Assertions.h"
13 #include "mozilla/Atomics.h"
14 #include "mozilla/Attributes.h"
15 #include "mozilla/RefCountType.h"
16 #include "mozilla/TypeTraits.h"
17 #if defined(MOZILLA_INTERNAL_API)
21 #if defined(MOZILLA_INTERNAL_API) && \
22 (defined(DEBUG) || defined(FORCE_BUILD_REFCNT_LOGGING))
23 #define MOZ_REFCOUNTED_LEAK_CHECKING
28 template<typename T
> class RefCounted
;
29 template<typename T
> class RefPtr
;
30 template<typename T
> class TemporaryRef
;
31 template<typename T
> class OutParamRef
;
32 template<typename T
> OutParamRef
<T
> byRef(RefPtr
<T
>&);
35 * RefCounted<T> is a sort of a "mixin" for a class T. RefCounted
36 * manages, well, refcounting for T, and because RefCounted is
37 * parameterized on T, RefCounted<T> can call T's destructor directly.
38 * This means T doesn't need to have a virtual dtor and so doesn't
41 * RefCounted<T> is created with refcount == 0. Newly-allocated
42 * RefCounted<T> must immediately be assigned to a RefPtr to make the
43 * refcount > 0. It's an error to allocate and free a bare
44 * RefCounted<T>, i.e. outside of the RefPtr machinery. Attempts to
45 * do so will abort DEBUG builds.
47 * Live RefCounted<T> have refcount > 0. The lifetime (refcounts) of
48 * live RefCounted<T> are controlled by RefPtr<T> and
49 * RefPtr<super/subclass of T>. Upon a transition from refcounted==1
50 * to 0, the RefCounted<T> "dies" and is destroyed. The "destroyed"
51 * state is represented in DEBUG builds by refcount==0xffffdead. This
52 * state distinguishes use-before-ref (refcount==0) from
53 * use-after-destroy (refcount==0xffffdead).
55 * Note that when deriving from RefCounted or AtomicRefCounted, you
56 * should add MOZ_DECLARE_REFCOUNTED_TYPENAME(ClassName) to the public
57 * section of your class, where ClassName is the name of your class.
61 const MozRefCountType DEAD
= 0xffffdead;
64 // When building code that gets compiled into Gecko, try to use the
65 // trace-refcount leak logging facilities.
66 #ifdef MOZ_REFCOUNTED_LEAK_CHECKING
70 static void logAddRef(const void* aPointer
, MozRefCountType aRefCount
,
71 const char* aTypeName
, uint32_t aInstanceSize
)
73 MOZ_ASSERT(aRefCount
!= DEAD
);
74 NS_LogAddRef(const_cast<void*>(aPointer
), aRefCount
, aTypeName
,
78 static void logRelease(const void* aPointer
, MozRefCountType aRefCount
,
79 const char* aTypeName
)
81 MOZ_ASSERT(aRefCount
!= DEAD
);
82 NS_LogRelease(const_cast<void*>(aPointer
), aRefCount
, aTypeName
);
87 // This is used WeakPtr.h as well as this file.
88 enum RefCountAtomicity
94 template<typename T
, RefCountAtomicity Atomicity
>
97 friend class RefPtr
<T
>;
100 RefCounted() : mRefCnt(0) {}
101 ~RefCounted() { MOZ_ASSERT(mRefCnt
== detail::DEAD
); }
104 // Compatibility with nsRefPtr.
107 // Note: this method must be thread safe for AtomicRefCounted.
108 MOZ_ASSERT(int32_t(mRefCnt
) >= 0);
109 #ifndef MOZ_REFCOUNTED_LEAK_CHECKING
112 const char* type
= static_cast<const T
*>(this)->typeName();
113 uint32_t size
= static_cast<const T
*>(this)->typeSize();
114 const void* ptr
= static_cast<const T
*>(this);
115 MozRefCountType cnt
= ++mRefCnt
;
116 detail::RefCountLogger::logAddRef(ptr
, cnt
, type
, size
);
122 // Note: this method must be thread safe for AtomicRefCounted.
123 MOZ_ASSERT(int32_t(mRefCnt
) > 0);
124 #ifndef MOZ_REFCOUNTED_LEAK_CHECKING
125 MozRefCountType cnt
= --mRefCnt
;
127 const char* type
= static_cast<const T
*>(this)->typeName();
128 const void* ptr
= static_cast<const T
*>(this);
129 MozRefCountType cnt
= --mRefCnt
;
130 // Note: it's not safe to touch |this| after decrementing the refcount,
132 detail::RefCountLogger::logRelease(ptr
, cnt
, type
);
135 // Because we have atomically decremented the refcount above, only
136 // one thread can get a 0 count here, so as long as we can assume that
137 // everything else in the system is accessing this object through
138 // RefPtrs, it's safe to access |this| here.
140 mRefCnt
= detail::DEAD
;
142 delete static_cast<const T
*>(this);
146 // Compatibility with wtf::RefPtr.
147 void ref() { AddRef(); }
148 void deref() { Release(); }
149 MozRefCountType
refCount() const { return mRefCnt
; }
150 bool hasOneRef() const
152 MOZ_ASSERT(mRefCnt
> 0);
157 mutable typename Conditional
<Atomicity
== AtomicRefCount
,
158 Atomic
<MozRefCountType
>,
159 MozRefCountType
>::Type mRefCnt
;
162 #ifdef MOZ_REFCOUNTED_LEAK_CHECKING
163 // Passing MOZ_OVERRIDE for the optional argument marks the typeName and
164 // typeSize functions defined by this macro as overrides.
165 #define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...) \
166 virtual const char* typeName() const __VA_ARGS__ { return #T; } \
167 virtual size_t typeSize() const __VA_ARGS__ { return sizeof(*this); }
169 #define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...)
172 // Note that this macro is expanded unconditionally because it declares only
173 // two small inline functions which will hopefully get eliminated by the linker
174 // in non-leak-checking builds.
175 #define MOZ_DECLARE_REFCOUNTED_TYPENAME(T) \
176 const char* typeName() const { return #T; } \
177 size_t typeSize() const { return sizeof(*this); }
179 } // namespace detail
182 class RefCounted
: public detail::RefCounted
<T
, detail::NonAtomicRefCount
>
187 static_assert(IsBaseOf
<RefCounted
, T
>::value
,
188 "T must derive from RefCounted<T>");
195 * AtomicRefCounted<T> is like RefCounted<T>, with an atomically updated
198 * NOTE: Please do not use this class, use NS_INLINE_DECL_THREADSAFE_REFCOUNTING
202 class AtomicRefCounted
:
203 public mozilla::detail::RefCounted
<T
, mozilla::detail::AtomicRefCount
>
208 static_assert(IsBaseOf
<AtomicRefCounted
, T
>::value
,
209 "T must derive from AtomicRefCounted<T>");
213 } // namespace external
216 * RefPtr points to a refcounted thing that has AddRef and Release
217 * methods to increase/decrease the refcount, respectively. After a
218 * RefPtr<T> is assigned a T*, the T* can be used through the RefPtr
219 * as if it were a T*.
221 * A RefPtr can forget its underlying T*, which results in the T*
222 * being wrapped in a temporary object until the T* is either
223 * re-adopted from or released by the temporary.
228 // To allow them to use unref()
229 friend class TemporaryRef
<T
>;
230 friend class OutParamRef
<T
>;
235 RefPtr() : mPtr(0) {}
236 RefPtr(const RefPtr
& aOther
) : mPtr(ref(aOther
.mPtr
)) {}
237 MOZ_IMPLICIT
RefPtr(const TemporaryRef
<T
>& aOther
) : mPtr(aOther
.take()) {}
238 MOZ_IMPLICIT
RefPtr(T
* aVal
) : mPtr(ref(aVal
)) {}
241 RefPtr(const RefPtr
<U
>& aOther
) : mPtr(ref(aOther
.get())) {}
243 ~RefPtr() { unref(mPtr
); }
245 RefPtr
& operator=(const RefPtr
& aOther
)
247 assign(ref(aOther
.mPtr
));
250 RefPtr
& operator=(const TemporaryRef
<T
>& aOther
)
252 assign(aOther
.take());
255 RefPtr
& operator=(T
* aVal
)
262 RefPtr
& operator=(const RefPtr
<U
>& aOther
)
264 assign(ref(aOther
.get()));
268 TemporaryRef
<T
> forget()
272 return TemporaryRef
<T
>(tmp
, DontRef());
275 T
* get() const { return mPtr
; }
276 operator T
*() const { return mPtr
; }
277 T
* operator->() const MOZ_NO_ADDREF_RELEASE_ON_RETURN
{ return mPtr
; }
278 T
& operator*() const { return *mPtr
; }
280 operator TemporaryRef
<U
>() { return TemporaryRef
<U
>(mPtr
); }
289 T
* MOZ_OWNING_REF mPtr
;
291 static MOZ_ALWAYS_INLINE T
* ref(T
* aVal
)
299 static MOZ_ALWAYS_INLINE
void unref(T
* aVal
)
308 * TemporaryRef<T> represents an object that holds a temporary
309 * reference to a T. TemporaryRef objects can't be manually ref'd or
310 * unref'd (being temporaries, not lvalues), so can only relinquish
311 * references to other objects, or unref on destruction.
316 // To allow it to construct TemporaryRef from a bare T*
317 friend class RefPtr
<T
>;
319 typedef typename RefPtr
<T
>::DontRef DontRef
;
322 MOZ_IMPLICIT
TemporaryRef(T
* aVal
) : mPtr(RefPtr
<T
>::ref(aVal
)) {}
323 TemporaryRef(const TemporaryRef
& aOther
) : mPtr(aOther
.take()) {}
326 TemporaryRef(const TemporaryRef
<U
>& aOther
) : mPtr(aOther
.take()) {}
328 ~TemporaryRef() { RefPtr
<T
>::unref(mPtr
); }
330 MOZ_WARN_UNUSED_RESULT T
* take() const
338 TemporaryRef(T
* aVal
, const DontRef
&) : mPtr(aVal
) {}
340 mutable T
* MOZ_OWNING_REF mPtr
;
342 TemporaryRef() = delete;
343 void operator=(const TemporaryRef
&) = delete;
347 * OutParamRef is a wrapper that tracks a refcounted pointer passed as
348 * an outparam argument to a function. OutParamRef implements COM T**
349 * outparam semantics: this requires the callee to AddRef() the T*
350 * returned through the T** outparam on behalf of the caller. This
351 * means the caller (through OutParamRef) must Release() the old
352 * object contained in the tracked RefPtr. It's OK if the callee
353 * returns the same T* passed to it through the T** outparam, as long
354 * as the callee obeys the COM discipline.
356 * Prefer returning TemporaryRef<T> from functions over creating T**
357 * outparams and passing OutParamRef<T> to T**. Prefer RefPtr<T>*
358 * outparams over T** outparams.
363 friend OutParamRef byRef
<T
>(RefPtr
<T
>&);
368 RefPtr
<T
>::unref(mRefPtr
.mPtr
);
372 operator T
**() { return &mTmp
; }
375 explicit OutParamRef(RefPtr
<T
>& p
) : mRefPtr(p
), mTmp(p
.get()) {}
380 OutParamRef() = delete;
381 OutParamRef
& operator=(const OutParamRef
&) = delete;
385 * byRef cooperates with OutParamRef to implement COM outparam semantics.
389 byRef(RefPtr
<T
>& aPtr
)
391 return OutParamRef
<T
>(aPtr
);
394 } // namespace mozilla
396 #endif /* mozilla_RefPtr_h */