mirror of
https://codeberg.org/comaps/comaps
synced 2025-12-21 13:53:37 +00:00
committed by
Konstantin Pastbin
parent
c9cbb64f12
commit
76ffc99abd
62
libs/base/scope_guard.hpp
Normal file
62
libs/base/scope_guard.hpp
Normal file
@@ -0,0 +1,62 @@
|
||||
/// @author Yury Melnichek mailto:melnichek@gmail.com
|
||||
/// @date 07.01.2005
|
||||
/// @brief See http://gzip.rsdn.ru/forum/Message.aspx?mid=389127&only=1.
|
||||
|
||||
#pragma once
|
||||
|
||||
namespace base
|
||||
{
|
||||
namespace impl
|
||||
{
|
||||
/// Base class for all ScopeGuards.
|
||||
class GuardBase
|
||||
{
|
||||
public:
|
||||
/// Disable ScopeGuard functionality on it's destruction
|
||||
void release() const
|
||||
{
|
||||
m_bDoRollback = false;
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
GuardBase() : m_bDoRollback(true)
|
||||
{
|
||||
}
|
||||
|
||||
// Do something in the destructor
|
||||
mutable bool m_bDoRollback;
|
||||
};
|
||||
|
||||
/// ScopeGuard for specific functor
|
||||
template <typename TFunctor> class GuardImpl : public GuardBase
|
||||
{
|
||||
public:
|
||||
explicit GuardImpl(TFunctor const & F) : m_Functor(F)
|
||||
{
|
||||
}
|
||||
|
||||
~GuardImpl()
|
||||
{
|
||||
if (m_bDoRollback)
|
||||
m_Functor();
|
||||
}
|
||||
|
||||
private:
|
||||
TFunctor m_Functor;
|
||||
};
|
||||
} // namespace impl
|
||||
|
||||
typedef impl::GuardBase const & scope_guard;
|
||||
|
||||
/// Create scope_guard
|
||||
template <typename TFunctor>
|
||||
impl::GuardImpl<TFunctor> make_scope_guard(TFunctor const & F)
|
||||
{
|
||||
return impl::GuardImpl<TFunctor>(F);
|
||||
}
|
||||
} // namespace base
|
||||
|
||||
#define SCOPE_GUARD(name, func) \
|
||||
::base::scope_guard name = base::make_scope_guard(func); \
|
||||
static_cast<void>(name)
|
||||
Reference in New Issue
Block a user