问题描述
我为C ++ 11编写了一个小实用程序类,我将其用作范围保护,以更容易处理异常安全和类似的事情。
I've written a small utility class for C++11 which I use as a scope guard for easier handling of exception safety and similar things.
似乎有点像一个黑客。但我很惊讶,我没有看到它在其他地方使用C ++ 11功能。我认为boost有类似的C ++ 98。
Seems somewhat like a hack. But I'm suprised I haven't seen it somewhere else using C++11 features. I think boost has something similar for C++98.
但是这是一个好主意吗?还是有我错过的潜在问题?是否已经有一个类似的解决方案(与C ++ 11功能)在boost或类似?
But is it a good idea? Or are there potential problems I have missed? Is there already a similar solution (with C++11 features) in boost or similar?
namespace detail
{
template<typename T>
class scope_exit : boost::noncopyable
{
public:
explicit scope_exit(T&& exitScope) : exitScope_(std::forward<T>(exitScope)){}
~scope_exit(){try{exitScope_();}catch(...){}}
private:
T exitScope_;
};
template <typename T>
scope_exit<T> create_scope_exit(T&& exitScope)
{
return scope_exit<T>(std::forward<T>(exitScope));
}
}
#define _UTILITY_EXIT_SCOPE_LINENAME_CAT(name, line) name##line
#define _UTILITY_EXIT_SCOPE_LINENAME(name, line) _UTILITY_EXIT_SCOPE_LINENAME_CAT(name, line)
#define UTILITY_SCOPE_EXIT(f) const auto& _UTILITY_EXIT_SCOPE_LINENAME(EXIT, __LINE__) = ::detail::create_scope_exit(f)
。
int main ()
{
ofstream myfile;
myfile.open ("example.txt");
UTILITY_SCOPE_EXIT([&]{myfile.close();}); // Make sure to close file even in case of exception
myfile << "Writing this to a file.\n"; // Imagine this could throw
return 0;
}
推荐答案
当然。相关主题是。
您不处理异常。
Alexandrescu长时间想出了。 Boost和 std :: tr1
都有一个名为和(使用自定义删除程序),可以让您完成此操作。
Alexandrescu came up with ScopeGuard a long time back. Both Boost and std::tr1
has a thing called scoped_ptr
and shared_ptr
(with a custom deleter) that allows you to accomplish just this.
这篇关于C ++ 11 scope exit guard,一个好主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!