L4Re Operating System Framework
Interface and Usage Documentation
Loading...
Searching...
No Matches
weak_ref
1// vi:set ft=cpp: -*- Mode: C++ -*-
2/*
3 * Copyright (C) 2015, 2017 Kernkonzept GmbH.
4 * Author(s): Sarah Hoffmann <sarah.hoffmann@kernkonzept.com>
5 * Alwexander Warg <alexander.warg@kernkonzept.com>
6 *
7 * This file is distributed under the terms of the GNU General Public
8 * License, version 2. Please see the COPYING-GPL-2 file for details.
9 */
10#pragma once
11
12#include "hlist"
13
14namespace cxx {
15
25class Weak_ref_base : public H_list_item_t<Weak_ref_base>
26{
27protected:
28 Weak_ref_base(void const *ptr = nullptr) : _obj(ptr) {}
29 void reset_hard() { _obj = nullptr; }
30 void const *_obj;
31
32public:
39 struct List : H_list_t<Weak_ref_base>
40 {
41 void reset()
42 {
43 while (!empty())
44 pop_front()->reset_hard();
45 }
46
47 ~List()
48 { reset(); }
49 };
50
51 explicit operator bool () const
52 { return _obj ? true : false; }
53};
54
55
95template <typename T>
96class Weak_ref : public Weak_ref_base
97{
98public:
99 T *get() const
100 { return reinterpret_cast<T*>(const_cast<void *>(_obj)); }
101
102 T *reset(T *n)
103 {
104 T *r = get();
105 if (r)
106 r->remove_weak_ref(this);
107
108 _obj = n;
109 if (n)
110 n->add_weak_ref(this);
111
112 return r;
113 }
114
115 Weak_ref(T *s = nullptr) : Weak_ref_base(s)
116 {
117 if (s)
118 s->add_weak_ref(this);
119 }
120
121 ~Weak_ref() { reset(0); }
122
123 void operator = (T *n)
124 { reset(n); }
125
126 Weak_ref(Weak_ref const &o) : Weak_ref_base(o._obj)
127 {
128 if (T *x = get())
129 x->add_weak_ref(this);
130 }
131
132 Weak_ref &operator = (Weak_ref const &o)
133 {
134 if (&o == this)
135 return *this;
136
137 reset(o.get());
138 return *this;
139 }
140
141 T &operator * () const { return get(); }
142 T *operator -> () const { return get(); }
143};
144
145class Weak_ref_obj
146{
147protected:
148 template <typename T> friend class Weak_ref;
149 mutable Weak_ref_base::List weak_references;
150
151 void add_weak_ref(Weak_ref_base *ref) const
152 { weak_references.push_front(ref); }
153
154 void remove_weak_ref(Weak_ref_base *ref) const
155 { weak_references.remove(ref); }
156};
157
158}
bool empty() const
Check if the list is empty.
Basic element type for a double-linked H_list.
Definition hlist:34
T * pop_front()
Remove and return the head element of the list.
Definition hlist:127
static void remove(T *e)
Remove the given element from its list.
Definition hlist:231
void push_front(T *e)
Add element to the front of the list.
Definition hlist:120
Generic (base) weak reference to some object.
Definition weak_ref:26
Typed weak reference to an object of type T.
Definition weak_ref:97
Our C++ library.
Definition arith:22
Double-linked list of typed H_list_item_t elements.
Definition hlist:260
The list type for keeping all weak references to an object.
Definition weak_ref:40