ScopeGuard : 安全清理資源


代碼轉自 : 
http://blog.csdn.net/pongba/article/details/7911997

// TestScopeGuard01.cpp : 定義控制檯應用程序的入口點。
//

#include "stdafx.h"
#include <functional>

namespace hh {
    class ScopeGuard
    {
    public:
        explicit ScopeGuard(std::function<void()> onExitScope)
            : onExitScope_(onExitScope), dismissed_(false)
        { }

        ~ScopeGuard()
        {
            if (!dismissed_)
            {
                onExitScope_();
            }
        }

        void Dismiss()
        {
            dismissed_ = true;
        }

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

    private: // noncopyable
        ScopeGuard(ScopeGuard const&);
        ScopeGuard& operator=(ScopeGuard const&);
    };
#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)
}


int main()
{
    using namespace hh;
    try {

        //ON_SCOPE_EXIT([]() {printf("正常退出,釋放資源\r\n"); });
        ScopeGuard onExit([]() {printf("正常退出,釋放資源\r\n"); });
        //throw 1;
        // 調用下面的函數,就不會執行 清理操作了
        onExit.Dismiss();
    }
    catch (...) {

    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章