]> git.ipfire.org Git - thirdparty/squid.git/blob - src/base/RefCount.h
SourceFormat Enforcement
[thirdparty/squid.git] / src / base / RefCount.h
1 /*
2 * Copyright (C) 1996-2014 The Squid Software Foundation and contributors
3 *
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
7 */
8
9 /* DEBUG: section -- Refcount allocator */
10
11 #ifndef SQUID_REFCOUNT_H_
12 #define SQUID_REFCOUNT_H_
13
14 // reference counting requires the Lock API on base classes
15 #include "base/Lock.h"
16
17 #include <iostream>
18
19 /**
20 * Template for Reference Counting pointers.
21 *
22 * Objects of type 'C' must inherit from 'RefCountable' in base/Lock.h
23 * which provides the locking interface used by reference counting.
24 */
25 template <class C>
26 class RefCount
27 {
28
29 public:
30 RefCount () : p_ (NULL) {}
31
32 RefCount (C const *p) : p_(p) { reference (*this); }
33
34 ~RefCount() {
35 dereference();
36 }
37
38 RefCount (const RefCount &p) : p_(p.p_) {
39 reference (p);
40 }
41
42 RefCount& operator = (const RefCount& p) {
43 // DO NOT CHANGE THE ORDER HERE!!!
44 // This preserves semantics on self assignment
45 C const *newP_ = p.p_;
46 reference(p);
47 dereference(newP_);
48 return *this;
49 }
50
51 bool operator !() const { return !p_; }
52
53 C * operator-> () const {return const_cast<C *>(p_); }
54
55 C & operator * () const {return *const_cast<C *>(p_); }
56
57 C const * getRaw() const {return p_; }
58
59 C * getRaw() {return const_cast<C *>(p_); }
60
61 bool operator == (const RefCount& p) const {
62 return p.p_ == p_;
63 }
64
65 bool operator != (const RefCount &p) const {
66 return p.p_ != p_;
67 }
68
69 private:
70 void dereference(C const *newP = NULL) {
71 /* Setting p_ first is important:
72 * we may be freed ourselves as a result of
73 * delete p_;
74 */
75 C const (*tempP_) (p_);
76 p_ = newP;
77
78 if (tempP_ && tempP_->unlock() == 0)
79 delete tempP_;
80 }
81
82 void reference (const RefCount& p) {
83 if (p.p_)
84 p.p_->lock();
85 }
86
87 C const *p_;
88
89 };
90
91 template <class C>
92 inline std::ostream &operator <<(std::ostream &os, const RefCount<C> &p)
93 {
94 if (p != NULL)
95 return os << p.getRaw() << '*' << p->LockCount();
96 else
97 return os << "NULL";
98 }
99
100 #endif /* SQUID_REFCOUNT_H_ */
101