Advertisement
Guest User

Finally FINALLY!

a guest
Jun 2nd, 2010
4,771
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.72 KB | None | 0 0
  1.  
  2. template<class F>
  3. struct finally_helper
  4. {
  5.     F f;
  6.     finally_helper(F &_f) : f(_f) {}
  7.     ~finally_helper() { f(); } 
  8. };
  9.  
  10. #define CONCAT2(X,Y) X##Y
  11. #define CONCAT(X,Y) CONCAT2(X,Y)
  12.  
  13. // gcc-4.5 chokes on this:
  14. // #define FINALLY2(BODY,F,V) finally_helper<decltype( [&]()BODY )> V( [&]()BODY )
  15. #define FINALLY2(BODY,F,V) auto F=[&]()BODY; finally_helper<decltype(F)> V(F)
  16. #define FINALLY(BODY) FINALLY2(BODY,CONCAT(finally_fn,__LINE__),CONCAT(finally_var,__LINE__))
  17.  
  18. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <assert.h>
  21. int main(int argc,char **argv)
  22. {  
  23.    
  24.     void *b=malloc(1000);
  25.     if (b) {
  26.         FINALLY({
  27.             printf("freeing b\n");
  28.             free(b);
  29.             b=0;
  30.         });
  31.         printf("working with b\n");
  32.     }
  33.     assert(b==0);
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement