Guest User

Untitled

a guest
Nov 23rd, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. #ifndef TOKEN_PASTE
  2. #define TOKEN_PASTE(x, y) x##y
  3. #define TOKEN_PASTE2(x, y) TOKEN_PASTE(x, y)
  4. #endif
  5.  
  6. template <typename L>
  7. struct scope_guard
  8. {
  9. L l_;
  10. bool invoked_{false};
  11.  
  12. scope_guard(L &&l)
  13. : l_(std::move(l))
  14. {
  15. }
  16.  
  17. ~scope_guard()
  18. {
  19. invoke();
  20. }
  21.  
  22. void invoke()
  23. {
  24. if (!invoked_)
  25. {
  26. l_();
  27. invoked_ = false;
  28. }
  29. }
  30.  
  31. void cancel()
  32. {
  33. invoked_ = true;
  34. }
  35. };
  36.  
  37. template <typename T>
  38. inline auto make_scope_guard(T &&l)
  39. {
  40. return scope_guard<T>(std::forward<T>(l));
  41. }
  42.  
  43. #define DEFER(...) auto TOKEN_PASTE2(__deferred, __COUNTER__) = make_scope_guard([&] { __VA_ARGS__ });
  44.  
  45. int main()
  46. {
  47. int fd = open("/proc/self/pagemap", O_RDONLY|O_LARGEFILE);
  48.  
  49. // DEFER(close(fd););
  50. // or
  51. // auto g = make_guard([fd]{ close(fd); });
  52. //
  53. // potentially g.cancel() or g.invoke() if needed
  54.  
  55.  
  56. return 0;
  57. }
Add Comment
Please, Sign In to add comment