pastebin - collaborative debugging tool
eckelmann.kpaste.net RSS


C++ "finally", like JAVA finally
Posted by Anonymous on Thu 6th Dec 2018 13:28
raw | new post

  1. /*
  2.  * JAVA "finally"-style exception-safe gargabe collection
  3.  * for C++11
  4.  *
  5.  * cxx -std=c++11 lambda_finally_test1.cpp
  6.  * Written by Roland Mainz <roland.mainz@nrubsig.org>
  7.  */
  8.  
  9. #include <functional>
  10.  
  11. #include <stdlib.h>
  12. #include <stdio.h>
  13.  
  14.  
  15. class finally
  16. {
  17.         std::function<void(void)> f;
  18.  
  19. public:
  20.         finally(const std::function<void(void)> &f) : f(f)
  21.         {
  22.         }
  23.  
  24.         ~finally()
  25.         {
  26.                 f();
  27.         }
  28. };
  29.  
  30.  
  31. int foo(int ac)
  32. {
  33.         int arg = ac;
  34.        
  35.         finally xdone([&]{ printf("#done\n"); });
  36.  
  37.         puts("#start.");
  38.  
  39.         {
  40.                 finally x1([&]{ puts("four"); });
  41.                
  42.                 puts("#one.");
  43.  
  44.                 {
  45.                         finally x2([&]{ printf("three %d\n", arg); });
  46.                         puts("#two.");
  47.                        
  48.                         arg = 7;
  49.                         throw "blabla_exception";
  50.                 }
  51.         }
  52.  
  53.         puts("#err_not_reachable.");
  54.         return EXIT_FAILURE;
  55. }
  56.  
  57.  
  58. int main(int ac, char *av[])
  59. {
  60.         int retcode = EXIT_SUCCESS;
  61.  
  62.         try
  63.         {
  64.                 retcode = foo(ac);
  65.         }
  66.         catch(...)
  67.         {
  68.         }
  69.        
  70.         return retcode;
  71. }

Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:

To highlight particular lines, prefix each line with {%HIGHLIGHT}





All content is user-submitted.
The administrators of this site (kpaste.net) are not responsible for their content.
Abuse reports should be emailed to us at