您的位置:首页 > 运维架构

使用ScopeGuard统一管理系统资源的释放

2016-12-12 00:00 489 查看
#include <algorithm>
#include <functional>

//作用域

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_;
//允许调用者选择可跳过执行onExitScope();
bool dismissed_;

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

//自动命名, 避免每次都要给class ScopeGuard实例命名的麻烦;
#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)

//使用举例

unsigned short Foo(const char *path)
{
FILE *pf = NULL;

//定义Lamda函数来实际释放资源(此例中为文件指针pf);

//如此, 在之后的其他描述中, 无论有无提前结束的情形, 均无需去显式表述pf资源的释放, 即简约又安全;
ON_SCOPE_EXIT( [&] () { if(pf) fclose(pf); } );

if(xxx) {

...

return -1;

}

...

if(yyy) {

...

return -2;

}

...

return 0;

}

注意, 需要c++11支持, 编译时使用-std=c++11参数;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++11