ScopeGuard : 安全清理资源


代码转自 : 
http://blog.csdn.net/pongba/article/details/7911997

// TestScopeGuard01.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include 

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;
}

你可能感兴趣的:(C++,有用的代码,C++)