From 6777c1469727b27d7909cd1aafee23458ba19431 Mon Sep 17 00:00:00 2001 From: Maxime Coste Date: Tue, 1 May 2018 22:38:51 +1000 Subject: [PATCH] Make OnScopeEnd valid even when non-copy elided OnScopeEnd was relying on copy elision to avoid temporary destructor calls that would run the scope end function too soon. --- src/utils.hh | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/utils.hh b/src/utils.hh index 9eced1c29..23afdeb19 100644 --- a/src/utils.hh +++ b/src/utils.hh @@ -65,11 +65,18 @@ class OnScopeEnd { public: [[gnu::always_inline]] - OnScopeEnd(T func) : m_func(std::move(func)) {} + OnScopeEnd(T func) : m_func{std::move(func)}, m_valid{true} {} [[gnu::always_inline]] - ~OnScopeEnd() { m_func(); } + OnScopeEnd(OnScopeEnd&& other) + : m_func{std::move(other.m_func)}, m_valid{other.m_valid} + { other.m_valid = false; } + + [[gnu::always_inline]] + ~OnScopeEnd() { if (m_valid) m_func(); } + private: + bool m_valid; T m_func; };