Loading...
Searching...
No Matches
weak_ref
// vi:set ft=cpp: -*- Mode: C++ -*-
/*
* Copyright (C) 2015, 2017, 2024 Kernkonzept GmbH.
* Author(s): Sarah Hoffmann <sarah.hoffmann@kernkonzept.com>
* Alexander Warg <alexander.warg@kernkonzept.com>
*
* License: see LICENSE.spdx (in this directory or the directories above)
*/
#pragma once
#include "hlist"
namespace cxx {
class Weak_ref_base : public H_list_item_t<Weak_ref_base>
{
protected:
Weak_ref_base(void const *ptr = nullptr) : _obj(ptr) {}
void reset_hard() { _obj = nullptr; }
void const *_obj;
public:
struct List : H_list_t<Weak_ref_base>
{
void reset()
{
while (!empty())
pop_front()->reset_hard();
}
~List()
{ reset(); }
};
explicit operator bool () const
{ return _obj ? true : false; }
};
template <typename T>
class Weak_ref : public Weak_ref_base
{
public:
T *get() const
{ return reinterpret_cast<T*>(const_cast<void *>(_obj)); }
T *reset(T *n)
{
T *r = get();
if (r)
r->remove_weak_ref(this);
_obj = n;
if (n)
n->add_weak_ref(this);
return r;
}
Weak_ref(T *s = nullptr) : Weak_ref_base(s)
{
if (s)
s->add_weak_ref(this);
}
~Weak_ref() { reset(0); }
void operator = (T *n)
{ reset(n); }
Weak_ref(Weak_ref const &o) : Weak_ref_base(o._obj)
{
if (T *x = get())
x->add_weak_ref(this);
}
Weak_ref &operator = (Weak_ref const &o)
{
if (&o == this)
return *this;
reset(o.get());
return *this;
}
T &operator * () const { return get(); }
T *operator -> () const { return get(); }
};
class Weak_ref_obj
{
protected:
template <typename T> friend class Weak_ref;
mutable Weak_ref_base::List weak_references;
void add_weak_ref(Weak_ref_base *ref) const
{ weak_references.push_front(ref); }
void remove_weak_ref(Weak_ref_base *ref) const
{ weak_references.remove(ref); }
};
}
cxx::Bits::Basic_list< Bits::Basic_list_policy< Weak_ref_base, H_list_item_t< Weak_ref_base > > >::empty
bool empty() const
Definition list_basics.h:126
cxx::H_list_item_t< Weak_ref_base >::H_list_item_t
H_list_item_t()
Definition hlist:30
cxx::H_list< Weak_ref_base, Bits::Basic_list_policy< Weak_ref_base, H_list_item_t< Weak_ref_base > > >::pop_front
Weak_ref_base * pop_front()
Definition hlist:116
cxx::H_list::remove
static void remove(T *e)
Remove the given element from its list.
Definition hlist:220
cxx::H_list::push_front
void push_front(T *e)
Add element to the front of the list.
Definition hlist:109
cxx::Weak_ref_base
Generic (base) weak reference to some object.
Definition weak_ref:25
cxx::Weak_ref
Typed weak reference to an object of type T.
Definition weak_ref:96
cxx
Our C++ library.
Definition arith:11
cxx::Weak_ref_base::List
The list type for keeping all weak references to an object.
Definition weak_ref:39