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