简单的RAII实现


13.3.1 Finally
The discipline required to represent a resource as an object of a class with a destructor have both
ered some. Again and again, people have inv ented ‘‘finally’’ language constructs for writing arbi
trary code to clean up after an exception. Such techniques are generally inferior to RAII because
they are ad hoc, but if you really want ad hoc, RAII can supply that also. First, we define a class
that will execute an arbitrary action from its destructor.
template<typename F>
struct Final_action {
Final_action(F f): clean{f} {}
˜Final_action() { clean(); }
F clean;
};
The ‘‘finally action’’ is provided as an argument to the constructor.
Next, we define a function that conveniently deduces the type of an action:
template<class F>
Final_action<F> finally(F f)
{
return Final_action<F>(f);
}
Finally, we can test finally():
void test()
// handle undiciplined resource acquisition
// demonstrate that arbitrar y actions are possible
{

intp = new int{7}; // probably should use a unique_ptr (§5.2)
intbuf = (int)malloc(100sizeof(int)); // C-style allocation

auto act1 = finally([&]{ delete p;
free(buf); //
C-style deallocation
cout<< "Goodby, Cruel world!\n";
}
);
int var = 0;
cout << "var = " << var << '\n';
//
nested block:
{
var = 1;
auto act2 = finally([&]{ cout<< "finally!\n"; var=7; });
cout << "var = " << var << '\n';
} //
act2 is invoked here
cout << "var = " << var << '\n';
} //
act1 is invoked here

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值