ScopeGuard.h 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /*
  2. * Copyright (c) 2016-present, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. */
  9. #pragma once
  10. #include <utility>
  11. namespace pzstd {
  12. /**
  13. * Dismissable scope guard.
  14. * `Function` must be callable and take no parameters.
  15. * Unless `dissmiss()` is called, the callable is executed upon destruction of
  16. * `ScopeGuard`.
  17. *
  18. * Example:
  19. *
  20. * auto guard = makeScopeGuard([&] { cleanup(); });
  21. */
  22. template <typename Function>
  23. class ScopeGuard {
  24. Function function;
  25. bool dismissed;
  26. public:
  27. explicit ScopeGuard(Function&& function)
  28. : function(std::move(function)), dismissed(false) {}
  29. void dismiss() {
  30. dismissed = true;
  31. }
  32. ~ScopeGuard() noexcept {
  33. if (!dismissed) {
  34. function();
  35. }
  36. }
  37. };
  38. /// Creates a scope guard from `function`.
  39. template <typename Function>
  40. ScopeGuard<Function> makeScopeGuard(Function&& function) {
  41. return ScopeGuard<Function>(std::forward<Function>(function));
  42. }
  43. }