<分区>
Possible Duplicate:
Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)
C++11 是否支持 try/catch/finally 构造?
我问是因为我找不到任何关于它的信息。
谢谢。
<分区>
Possible Duplicate:
Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)
C++11 是否支持 try/catch/finally 构造?
我问是因为我找不到任何关于它的信息。
谢谢。
最佳答案
这不是放弃 RAII 的借口,但在例如:使用非 RAII 感知 API:
template<typename Functor>
struct finally_guard {
finally_guard(Functor f)
: functor(std::move(f))
, active(true)
{}
finally_guard(finally_guard&& other)
: functor(std::move(other.functor))
, active(other.active)
{ other.active = false; }
finally_guard& operator=(finally_guard&&) = delete;
~finally_guard()
{
if(active)
functor();
}
Functor functor;
bool active;
};
template<typename F>
finally_guard<typename std::decay<F>::type>
finally(F&& f)
{
return { std::forward<F>(f) };
}
用法:
auto resource = /* acquire */;
auto guard = finally([&resource] { /* cleanup */ });
// using just
// finally([&resource] { /* cleanup */ });
// is wrong, as usual
请注意,如果您不需要翻译或以其他方式处理异常,则不需要 try
block 。
虽然我的示例使用了 C++11 功能,但 C++03 也提供了相同的通用功能(尽管没有 lambda)。
关于c++ - try catch finally construct - 它是在 C++11 中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7779652/