ScopeGuard
来源:互联网 发布:英国海军实力知乎 编辑:程序博客网 时间:2024/06/15 09:30
ScopeGuard的有个比较能用的上的地方就是,如果需要退出时执行某个操作,可以和方便的使用,而不需要用try finally。不管里面是否抛出异常,都会执行到我们必须执行的函数
实现也是利用了构造和析构函数,在构造函数中,将需要调用的函数地址传入,在析构时调用
class ScopeGuardImplBase
{
/// Copy-assignment operator is not implemented and private.
ScopeGuardImplBase& operator =(const ScopeGuardImplBase&);
protected:
~ScopeGuardImplBase()
{}
/// Copy-constructor takes over responsibility from other ScopeGuard.
ScopeGuardImplBase(const ScopeGuardImplBase& other) throw()
: dismissed_(other.dismissed_)
{
other.Dismiss();
}
template <typename J>
static void SafeExecute(J& j) throw()
{
if (!j.dismissed_)
try
{
j.Execute();
}
catch(...)
{}
}
mutable bool dismissed_;
public:
ScopeGuardImplBase() throw() : dismissed_(false)
{}
void Dismiss() const throw()
{
dismissed_ = true;
}
};
没有参数的函数指针的实现
template <typename F>
class ScopeGuardImpl0 : public ScopeGuardImplBase
{
public:
static ScopeGuardImpl0<F> MakeGuard(F fun)
{
return ScopeGuardImpl0<F>(fun);
}
~ScopeGuardImpl0() throw()
{
SafeExecute(*this);
}
void Execute()
{
fun_();
}
protected:
ScopeGuardImpl0(F fun) : fun_(fun)
{}
F fun_;
};
也可以出一个全局的工厂构造
template <typename F>
inline ScopeGuardImpl0<F> MakeGuard(F fun)
{
return ScopeGuardImpl0<F>::MakeGuard(fun);
}
多个参数,成员函数都可以类似扩展实现
使用,函数退出时候肯定会执行HasNone()函数了
void DoStandaloneFunctionTests()
{
::Loki::ScopeGuard guard0 = ::Loki::MakeGuard( &HasNone );
}
另外不想执行的话可以通过guard0.Dismiss();放弃
- ScopeGuard
- ScopeGuard : 安全清理资源
- ScopeGuard : 安全清理资源
- 泛化的ScopeGuard模板类
- 用ScopeGuard简化异常安全代码
- C++异常处理第四篇 Loki::ScopeGuard
- 使用ScopeGuard在运行环境中监测内部变量
- 用scopeguard库来保证Exception-Safe Code
- 永久改变你写异常安全代码的方式(神奇的Loki::ScopeGuard)
- 永久改变你写异常安全代码的方式(神奇的Loki::ScopeGuard)
- 永久改变你写异常安全代码的方式(神奇的Loki::ScopeGuard)
- c++异常处理第四篇---不使用try catch语句,使用Loki::ScopeGuard
- 每天进步一点点——C++11中使用lambda表达式实现一个简单的ScopeGuard
- 永久改变你写异常安全代码的方式(神奇的Loki::ScopeGuard)
- 如何退出函数时再做一些固定的事情(比如释放内存)--scopeguard
- 【Hadoop系列】第二章:安装Hadoop(上)单机版Hadoop
- 【矩阵快速幂】ZOJ 3690 Choosing number
- 如何在android studio中导入外部包
- 预言性的基于事例推理技术
- 打印菱形 字母金字塔和杨辉三角
- ScopeGuard
- MapReduce原理及运行流程回顾
- cmd 连接db2
- php exec python script not working [Solved]
- [异能程序员]第三章 异能初现(第三更)
- Compile FFmpeg on Ubuntu
- LeetCode #7 Reverse Integer
- php:顺序查找和二分查找
- [异能程序员]第四章 偶遇(第四更)