Advertisement
GeneralGDA

SCOPE EXIT

Dec 16th, 2016
398
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.25 KB | None | 0 0
  1. #pragma once
  2.  
  3. // https://www.youtube.com/watch?v=WjTrfoiB0MQ
  4.  
  5. #include <utility>
  6.  
  7. template<typename T>
  8. class ScopeGuard final
  9. {
  10. public:
  11.    
  12.     explicit ScopeGuard(T onExit)
  13.         : ready_(true)
  14.         , onExit_(onExit)
  15.     {
  16.     }
  17.    
  18.     ScopeGuard(ScopeGuard&& other) noexcept
  19.         : ready_(true)
  20.         , onExit_(other.onExit_)
  21.     {
  22.         other.ready_ = false;
  23.     }
  24.    
  25.     ~ScopeGuard()
  26.     {
  27.         if (ready_)
  28.         {
  29.             onExit_();
  30.             ready_ = false;
  31.         }
  32.     }
  33.  
  34.     ScopeGuard() = delete;
  35.     ScopeGuard(ScopeGuard& other) = delete;
  36.     ScopeGuard& operator=(ScopeGuard&& other) = delete;
  37.     ScopeGuard& operator=(const ScopeGuard& other) = delete;
  38.  
  39. private:
  40.    
  41.     bool ready_;
  42.     T onExit_;
  43.  
  44. };
  45.  
  46. namespace detail
  47. {
  48.     enum class ScopeGuardOnExit {};
  49.  
  50.     template<typename Function>
  51.     ScopeGuard<Function> operator+(ScopeGuardOnExit, Function&& function)
  52.     {
  53.         return ScopeGuard<Function>(std::forward<Function>(function));
  54.     }
  55. }
  56.  
  57. #define CONCATENATE_IMPL(s1, s2) s1##s2
  58. #define CONCATENATE(s1, s2) CONCATENATE_IMPL(s1, s2)
  59.  
  60. #ifdef __COUNTER__
  61. #define ANONYMOUS_VARIABLE(string) CONCATINATE(string, __COUNTER__)
  62. #else
  63. #define ANONYMOUS_VARIABLE(string) CONCATINATE(string, __LINE__)
  64. #endif
  65.  
  66. #define SCOPE_EXIT auto ANONIMOUS_VARIABLE(SCOPE_EXIT_STATE) = ::detail::ScopeGuardOnExit + (&)[]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement