• Home
  • History
  • Annotate
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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  
8  #ifndef SkScopeExit_DEFINED
9  #define SkScopeExit_DEFINED
10  
11  #include "SkTypes.h"
12  #include "SkMacros.h"
13  
14  #include <functional>
15  
16  /** SkScopeExit calls a std:::function<void()> in its destructor. */
17  class SkScopeExit {
18  public:
SkScopeExit(std::function<void ()> f)19      SkScopeExit(std::function<void()> f) : fFn(std::move(f)) {}
SkScopeExit(SkScopeExit && that)20      SkScopeExit(SkScopeExit&& that) : fFn(std::move(that.fFn)) {}
21  
~SkScopeExit()22      ~SkScopeExit() {
23          if (fFn) {
24              fFn();
25          }
26      }
27  
clear()28      void clear() { fFn = {}; }
29  
30      SkScopeExit& operator=(SkScopeExit&& that) {
31          fFn = std::move(that.fFn);
32          return *this;
33      }
34  
35  private:
36      std::function<void()> fFn;
37  
38      SkScopeExit(           const SkScopeExit& ) = delete;
39      SkScopeExit& operator=(const SkScopeExit& ) = delete;
40  };
41  
42  /**
43   * SK_AT_SCOPE_EXIT(stmt) evaluates stmt when the current scope ends.
44   *
45   * E.g.
46   *    {
47   *        int x = 5;
48   *        {
49   *           SK_AT_SCOPE_EXIT(x--);
50   *           SkASSERT(x == 5);
51   *        }
52   *        SkASSERT(x == 4);
53   *    }
54   */
55  #define SK_AT_SCOPE_EXIT(stmt)                              \
56      SkScopeExit SK_MACRO_APPEND_LINE(at_scope_exit_)([&]() { stmt; })
57  
58  #endif  // SkScopeExit_DEFINED
59