SkScopeExit.h 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * Copyright 2016 Google Inc.
  3. *
  4. * Use of this source code is governed by a BSD-style license that can be
  5. * found in the LICENSE file.
  6. */
  7. #ifndef SkScopeExit_DEFINED
  8. #define SkScopeExit_DEFINED
  9. #include "include/core/SkTypes.h"
  10. #include "include/private/SkMacros.h"
  11. #include <functional>
  12. /** SkScopeExit calls a std:::function<void()> in its destructor. */
  13. class SkScopeExit {
  14. public:
  15. SkScopeExit() = default;
  16. SkScopeExit(std::function<void()> f) : fFn(std::move(f)) {}
  17. SkScopeExit(SkScopeExit&& that) : fFn(std::move(that.fFn)) {}
  18. ~SkScopeExit() {
  19. if (fFn) {
  20. fFn();
  21. }
  22. }
  23. void clear() { fFn = {}; }
  24. SkScopeExit& operator=(SkScopeExit&& that) {
  25. fFn = std::move(that.fFn);
  26. return *this;
  27. }
  28. private:
  29. std::function<void()> fFn;
  30. SkScopeExit( const SkScopeExit& ) = delete;
  31. SkScopeExit& operator=(const SkScopeExit& ) = delete;
  32. };
  33. /**
  34. * SK_AT_SCOPE_EXIT(stmt) evaluates stmt when the current scope ends.
  35. *
  36. * E.g.
  37. * {
  38. * int x = 5;
  39. * {
  40. * SK_AT_SCOPE_EXIT(x--);
  41. * SkASSERT(x == 5);
  42. * }
  43. * SkASSERT(x == 4);
  44. * }
  45. */
  46. #define SK_AT_SCOPE_EXIT(stmt) \
  47. SkScopeExit SK_MACRO_APPEND_LINE(at_scope_exit_)([&]() { stmt; })
  48. #endif // SkScopeExit_DEFINED