RAII技法的工具类scope_guard

发布时间 2023-07-02 21:53:17作者: 算你牛
#pragma once

/*************************************************************************************
描 述:RAII技法的工具类
使 用 说 明:
//资 源 释 放
void foo()
{
HANDLE h = OpenFile(...);
ON_SCOPE_EXIT([&]{ CloseHandle(h); });
... // use the file
} //when the function is executed, it will automatically CloseHandle(h);

//函 数 回 滚:
void foo()
{
ScopeGuard onFailureRollback( rollbackFunction );
... // do something that could fail
onFailureRollback.Dismiss(); //stop the rollback
}
*************************************************************************************/
#include <functional> //std::function

class ScopeGuard {
public:
explicit ScopeGuard(std::function<void()> onExitScope) : onExitScope_(onExitScope), dismissed_(false)
{
}
~ScopeGuard()
{
if (!dismissed_)
{
onExitScope_();
}
}
void Dismiss()
{
dismissed_ = true;
}

public: // noncopyable
ScopeGuard(ScopeGuard const&) = delete;
ScopeGuard& operator=(ScopeGuard const&) = delete;

private:
std::function<void()> onExitScope_;
bool dismissed_;
};

#define SCOPEGUARD_LINENAME_CAT(name, line) name##line
#define SCOPEGUARD_LINENAME(name, line) SCOPEGUARD_LINENAME_CAT(name, line)
#define ON_SCOPE_EXIT(callback) ScopeGuard SCOPEGUARD_LINENAME(EXIT, __LINE__)(callback)