为什么80%的码农都做不了架构师?>>>
#include
#include
//作用域
class ScopeGuard
{
public:
explicit ScopeGuard(std::function
: onExitScope_(onExitScope), dismissed_(false)
{}
~ScopeGuard()
{
if(!dismissed_)
onExitScope_();
}
void Dismiss() { dismissed_ = true; }
private:
std::function
//允许调用者选择可跳过执行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参数;