]>
git.saurik.com Git - apple/security.git/blob - cdsa/cdsa_utilities/refcount.h
2 * Copyright (c) 2000-2001 Apple Computer, Inc. All Rights Reserved.
4 * The contents of this file constitute Original Code as defined in and are
5 * subject to the Apple Public Source License Version 1.2 (the 'License').
6 * You may not use this file except in compliance with the License. Please obtain
7 * a copy of the License at http://www.apple.com/publicsource and read it before
10 * This Original Code and all software distributed under the License are
11 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS
12 * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT
13 * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
14 * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the
15 * specific language governing rights and limitations under the License.
21 Based on code donated by Perry Kiehtreiber
28 #include <Security/threading.h>
34 // RefCount/RefPointer - a simple reference counting facility.
36 // To make an object reference-counted, derive it from RefCount. To track refcounted
37 // objects, use RefPointer<TheType>, where TheType must be derived from RefCount.
39 // RefCount is thread safe - any number of threads can hold and manipulate references
40 // in parallel. It does however NOT protect the contents of your object - just the
41 // reference count itself. If you need to share your object contents, you must engage
42 // in appropriate locking yourself.
44 // There is no (thread safe) way to determine whether you are the only thread holding
45 // a pointer to a particular RefCount object.
50 // Base class for reference counted objects
54 RefCount() : mRefCount(0) { }
57 template <class T
> friend class RefPointer
;
59 void ref() const { ++mRefCount
; }
60 unsigned int unref() const { return --mRefCount
; }
63 mutable AtomicCounter
<unsigned int> mRefCount
;
68 // A pointer type supported by reference counts.
69 // T must be derived from RefCount.
74 RefPointer() : ptr(0) {} // default to NULL pointer
75 RefPointer(const RefPointer
& p
) { if (p
) p
->ref(); ptr
= p
.ptr
; }
76 RefPointer(T
*p
) { if (p
) p
->ref(); ptr
= p
; }
78 ~RefPointer() { release(); }
80 RefPointer
& operator = (const RefPointer
& p
) { setPointer(p
.ptr
); return *this; }
81 RefPointer
& operator = (T
* p
) { setPointer(p
); return *this; }
83 // dereference operations
84 operator T
* () const { return ptr
; }
85 T
* operator -> () const { return ptr
; }
86 T
& operator * () const { return *ptr
; }
89 void release() { if (ptr
&& ptr
->unref() == 0) delete ptr
; }
90 void setPointer(T
*p
) { if (p
) p
->ref(); release(); ptr
= p
; }
95 } // end namespace Security