fork download
  1. #include <functional>
  2.  
  3. #include <fcntl.h>
  4. #include <sys/types.h>
  5. #include <unistd.h>
  6.  
  7. template<typename F>
  8. class finally
  9. {
  10. public:
  11. template<typename... Args>
  12. finally<F>(F action, Args&&... args) :
  13. _action([action, &args...]{ action(std::forward<Args>(args)...); }) {}
  14.  
  15. ~finally()
  16. try
  17. {
  18. if (enabled)
  19. _action();
  20. }
  21. catch (...)
  22. {
  23. // Logging and stuff
  24. }
  25.  
  26. bool enabled = true;
  27.  
  28. private:
  29. std::function<void()> _action;
  30. };
  31.  
  32. int main()
  33. {
  34. int fd = open("/proc/mounts", O_RDONLY);
  35. finally<int(int)> f(close, fd);
  36. }
Success #stdin #stdout 0s 3408KB
stdin
Standard input is empty
stdout
Standard output is empty