halcanary | 4871f22 | 2016-08-26 13:17:44 -0700 | [diff] [blame] | 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 | |
| 13 | /** |
| 14 | * SK_AT_SCOPE_EXIT(stmt) evaluates stmt when the current scope ends. |
| 15 | * |
| 16 | * E.g. |
| 17 | * { |
| 18 | * int x = 5; |
| 19 | * { |
| 20 | * SK_AT_SCOPE_EXIT(x--); |
| 21 | * SkASSERT(x == 5); |
| 22 | * } |
| 23 | * SkASSERT(x == 4); |
| 24 | * } |
| 25 | */ |
| 26 | template <typename Fn> |
| 27 | class SkScopeExit { |
| 28 | public: |
| 29 | SkScopeExit(Fn f) : fFn(std::move(f)) {} |
| 30 | ~SkScopeExit() { fFn(); } |
| 31 | |
| 32 | private: |
| 33 | Fn fFn; |
| 34 | |
| 35 | SkScopeExit( const SkScopeExit& ) = delete; |
| 36 | SkScopeExit& operator=(const SkScopeExit& ) = delete; |
| 37 | SkScopeExit( SkScopeExit&&) = delete; |
| 38 | SkScopeExit& operator=( SkScopeExit&&) = delete; |
| 39 | }; |
| 40 | |
| 41 | template <typename Fn> |
| 42 | inline SkScopeExit<Fn> SkMakeScopeExit(Fn&& fn) { |
| 43 | return {std::move(fn)}; |
| 44 | } |
| 45 | |
| 46 | #define SK_AT_SCOPE_EXIT(stmt) \ |
| 47 | SK_UNUSED auto&& SK_MACRO_APPEND_LINE(at_scope_exit_) = \ |
| 48 | SkMakeScopeExit([&]() { stmt; }); |
| 49 | |
| 50 | #endif // SkScopeExit_DEFINED |