/* * JAVA "finally"-style exception-safe gargabe collection * for C++11 * * cxx -std=c++11 lambda_finally_test1.cpp * Written by Roland Mainz */ #include #include #include class finally { std::function f; public: finally(const std::function &f) : f(f) { } ~finally() { f(); } }; int foo(int ac) { int arg = ac; finally xdone([&]{ printf("#done\n"); }); puts("#start."); { finally x1([&]{ puts("four"); }); puts("#one."); { finally x2([&]{ printf("three %d\n", arg); }); puts("#two."); arg = 7; throw "blabla_exception"; } } puts("#err_not_reachable."); return EXIT_FAILURE; } int main(int ac, char *av[]) { int retcode = EXIT_SUCCESS; try { retcode = foo(ac); } catch(...) { } return retcode; }