]>
git.ipfire.org Git - thirdparty/squid.git/blob - src/base/RefCount.h
2 * Copyright (C) 1996-2022 The Squid Software Foundation and contributors
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.
9 /* DEBUG: section -- Refcount allocator */
11 #ifndef SQUID_REFCOUNT_H_
12 #define SQUID_REFCOUNT_H_
14 // reference counting requires the Lock API on base classes
15 #include "base/Lock.h"
20 * Template for Reference Counting pointers.
22 * Objects of type 'C' must inherit from 'RefCountable' in base/Lock.h
23 * which provides the locking interface used by reference counting.
30 RefCount () : p_ (nullptr) {}
32 RefCount (C
const *p
) : p_(p
) { reference (*this); }
38 RefCount (const RefCount
&p
) : p_(p
.p_
) {
42 RefCount (RefCount
&&p
) : p_(std::move(p
.p_
)) {
46 /// Base::Pointer = Derived::Pointer
47 template <class Other
>
48 RefCount(const RefCount
<Other
> &p
): p_(p
.getRaw()) {
52 RefCount
& operator = (const RefCount
& p
) {
53 // DO NOT CHANGE THE ORDER HERE!!!
54 // This preserves semantics on self assignment
55 C
const *newP_
= p
.p_
;
61 RefCount
& operator = (RefCount
&& p
) {
69 explicit operator bool() const { return p_
; }
71 bool operator !() const { return !p_
; }
73 C
* operator-> () const {return const_cast<C
*>(p_
); }
75 C
& operator * () const {
77 return *const_cast<C
*>(p_
);
80 C
* getRaw() const { return const_cast<C
*>(p_
); }
82 bool operator == (const RefCount
& p
) const {
86 bool operator != (const RefCount
&p
) const {
91 void dereference(C
const *newP
= nullptr) {
92 /* Setting p_ first is important:
93 * we may be freed ourselves as a result of
96 C
const (*tempP_
) (p_
);
99 if (tempP_
&& tempP_
->unlock() == 0)
103 void reference (const RefCount
& p
) {
113 inline std::ostream
&operator <<(std::ostream
&os
, const RefCount
<C
> &p
)
116 return os
<< p
.getRaw() << '*' << p
->LockCount();
121 #endif /* SQUID_REFCOUNT_H_ */