Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- template<class F>
- struct finally_helper
- {
- F f;
- finally_helper(F &_f) : f(_f) {}
- ~finally_helper() { f(); }
- };
- #define CONCAT2(X,Y) X##Y
- #define CONCAT(X,Y) CONCAT2(X,Y)
- // gcc-4.5 chokes on this:
- // #define FINALLY2(BODY,F,V) finally_helper<decltype( [&]()BODY )> V( [&]()BODY )
- #define FINALLY2(BODY,F,V) auto F=[&]()BODY; finally_helper<decltype(F)> V(F)
- #define FINALLY(BODY) FINALLY2(BODY,CONCAT(finally_fn,__LINE__),CONCAT(finally_var,__LINE__))
- #include <stdio.h>
- #include <stdlib.h>
- #include <assert.h>
- int main(int argc,char **argv)
- {
- void *b=malloc(1000);
- if (b) {
- FINALLY({
- printf("freeing b\n");
- free(b);
- b=0;
- });
- printf("working with b\n");
- }
- assert(b==0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement