From 113acd7bba5481565dad1862c2e883251571334d Mon Sep 17 00:00:00 2001 From: arkpar Date: Fri, 12 Jun 2015 18:12:21 +0200 Subject: [PATCH] made signals/handler not dependent on destruction order --- libethcore/Common.h | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/libethcore/Common.h b/libethcore/Common.h index 64eb6de29..6f23cb0e8 100644 --- a/libethcore/Common.h +++ b/libethcore/Common.h @@ -123,28 +123,43 @@ struct ImportRequirements class Signal { public: + using Callback = std::function; + class HandlerAux { friend class Signal; public: ~HandlerAux() { if (m_s) m_s->m_fire.erase(m_i); m_s = nullptr; } + void reset() { m_s = nullptr; } + void fire() { m_h(); } private: - HandlerAux(unsigned _i, Signal* _s): m_i(_i), m_s(_s) {} + HandlerAux(unsigned _i, Signal* _s, Callback const& _h): m_i(_i), m_s(_s), m_h(_h) {} unsigned m_i = 0; Signal* m_s = nullptr; + Callback m_h; }; - using Callback = std::function; + ~Signal() + { + for (auto const& h : m_fire) + h.second->reset(); + } - std::shared_ptr add(Callback const& _h) { auto n = m_fire.empty() ? 0 : (m_fire.rbegin()->first + 1); m_fire[n] = _h; return std::shared_ptr(new HandlerAux(n, this)); } + std::shared_ptr add(Callback const& _h) + { + auto n = m_fire.empty() ? 0 : (m_fire.rbegin()->first + 1); + auto h = std::shared_ptr(new HandlerAux(n, this, _h)); + m_fire[n] = h; + return h; + } - void operator()() { for (auto const& f: m_fire) f.second(); } + void operator()() { for (auto const& f: m_fire) f.second->fire(); } private: - std::map m_fire; + std::map> m_fire; }; using Handler = std::shared_ptr;