在退出作用域时做一些事
Boost.ScopeExit库
由于种种原因,C++中没有Java或C#中的try{}finally{}语句,虽然有SEH,可以实现finally效果,但是可定制性太差,不尽人意。
SEH实现的finally语句
__try { throw std::bad_exception(); } __finally { cout << "in finally" << endl; }
使用Boost.ScopeExit库可以完美实现这一功能,功能类似于Golang的defer关键字
cout << "before boost scope" << endl; bool bClosed = false; BOOST_SCOPE_EXIT(bClosed) { cout << "in boost scope" << endl; bClosed = true; } BOOST_SCOPE_EXIT_END bClosed = false; cout << "after boost scope" << endl;
变量bClosed通过BOOST_SCOPE_EXIT(bClosed)按值传递,当程序离开执行的作用域时,"BOOST_SCOPE_EXIT{"与"}BOOST_SCOPE_EXIT_END"之间的代码将被执行。如果希望按引用传递值,那么要在BOOST_SCOPE_EXIT宏中使用&符号。如果想传递多个值,用逗号将它们分开即可。
查看boost库的源码BOOST_SCOPE_EXIT宏使用_VA_ARGS_不定参收集参数,所以()中的内容,按照不定参函数的参数规则填写即可。
Boost.ScopeExit库不在堆上分配任何额外内存,并且不使用虚函数,所以对程序执行性能没有任何影响。
#include <boost\scope_exit.hpp> static bool TestScope() { cout << "before boost scope" << endl; bool bClosed = false; BOOST_SCOPE_EXIT(bClosed) { cout << "in boost scope" << endl; bClosed = true; } BOOST_SCOPE_EXIT_END bClosed = false; cout << "after boost scope" << endl; return bClosed; } static void TestSEH() { __try { throw std::bad_exception(); cout << "never get here" << endl; } __finally { cout << "in finally" << endl; } cout << "out of finally" << endl; }