From a13474cd11283ae648e0dcaa156ce9058df15aa1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roman=20Smr=C5=BE?= Date: Wed, 22 Feb 2023 20:58:39 +0100 Subject: Pass weak pointer of HeadBhv to callback --- include/erebos/storage.h | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) (limited to 'include/erebos/storage.h') diff --git a/include/erebos/storage.h b/include/erebos/storage.h index 01aeada..c506dfd 100644 --- a/include/erebos/storage.h +++ b/include/erebos/storage.h @@ -528,6 +528,7 @@ void filterAncestors(std::vector> & xs) } template class WatchedHead; +template class HeadBhv; template class Head @@ -562,8 +563,13 @@ template class WatchedHead : public Head { friend class Head; + friend class HeadBhv; + + WatchedHead(const Head & h): + Head(h), watcherId(-1) {} WatchedHead(const Head & h, int watcherId): Head(h), watcherId(watcherId) {} + int watcherId; public: @@ -588,15 +594,26 @@ class HeadBhv : public BhvSource { public: HeadBhv(const Head & head): - whead(head.watch([this] (const Head & cur) { - BhvCurTime ctime; - whead = cur; - BhvImplBase::updated(ctime); - })) {} + whead(head) + {} T get(const BhvCurTime &, const std::monostate &) const { return *whead; } private: + friend class Head; + + void init() + { + whead = whead.watch([wp = weak_ptr(BhvImplBase::shared_from_this()), this] (const Head & cur) { + // make sure this object still exists + if (auto ptr = wp.lock()) { + BhvCurTime ctime; + whead = cur; + BhvImplBase::updated(ctime); + } + }); + } + WatchedHead whead; }; @@ -665,7 +682,9 @@ template Bhv Head::behavior() const { auto cur = reload(); - return make_shared>(cur ? *cur : *this); + auto ret = make_shared>(cur ? *cur : *this); + ret->init(); + return ret; } template -- cgit v1.2.3