Guest User

Untitled

a guest
Dec 17th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. #include <cstdio>
  2. #include <cstdlib>
  3. #include <memory>
  4.  
  5. #include <iostream>
  6. #include <string>
  7. template <typename Lambda>
  8. class ScopeGuard
  9. {
  10. public:
  11. ScopeGuard(Lambda&& func)
  12. : committed_(false) // Please one line per variable
  13. // Just like in normal code
  14. // were you declare one variable per line.
  15. , valid_(true)
  16. , rollbackFunc_(std::move(func)) // Need the move again.
  17. {} ~ScopeGuard() noexcept
  18. {
  19. if (valid_ && !committed_)
  20. rollbackFunc_();
  21. }
  22.  
  23. ScopeGuard(const ScopeGuard&) = delete;
  24. ScopeGuard& operator=(const ScopeGuard&) = delete;
  25.  
  26. ScopeGuard(ScopeGuard&& other) noexcept
  27. : committed_(false)
  28. , valid_(false)
  29. , rollbackFunc_([]() {})
  30. {
  31. swap(other);
  32. }
  33.  
  34. ScopeGuard& operator=(ScopeGuard&& other) noexcept
  35. {
  36. swap(other);
  37. other.valid_ = false;
  38. return *this;
  39. }
  40.  
  41. void swap(ScopeGuard& other) noexcept
  42. {
  43. using std::swap;
  44. swap(committed_, other.committed_);
  45. swap(valid_, other.valid_);
  46. swap(rollbackFunc_, other.rollbackFunc_);
  47. }
  48.  
  49. void commit() { committed_ = true; }
  50.  
  51. private:
  52. bool committed_;
  53. bool valid_;
  54. Lambda rollbackFunc_;
  55. };
  56.  
  57. template <typename Lambda>
  58. ScopeGuard<Lambda> makeScopeGuard(Lambda&& func)
  59. {
  60. return ScopeGuard<Lambda>(std::move(func)); // Need the move here
  61. // a named value is not an r-value ref.
  62. }
  63.  
  64.  
  65. #define MY_CONCATENATE_NX(A, B) A ## B
  66. #define MY_CONCATENATE(A, B) MY_CONCATENATE_NX(A, B)
  67.  
  68. #define SCOPE_EXIT(f) auto MY_CONCATENATE(EXIT, __LINE__) = makeScopeGuard(f);
  69.  
  70. void test() {
  71. auto guard1 = makeScopeGuard([]() { });
  72. auto guard2 = makeScopeGuard([]() { });
  73. guard2 = guard1; // can not move assign.
  74.  
  75. }
  76. int main() {
  77. test();
  78.  
  79. return EXIT_SUCCESS;
  80. }
Add Comment
Please, Sign In to add comment