Dmitriy Ivanov | a3ad450 | 2014-07-29 14:21:45 -0700 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright (C) 2014 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #ifndef SCOPE_GUARD_H |
| 18 | #define SCOPE_GUARD_H |
| 19 | |
| 20 | // TODO: include explicit std::move when it becomes available |
| 21 | template<typename F> |
| 22 | class ScopeGuard { |
| 23 | public: |
| 24 | ScopeGuard(F f) : f_(f), active_(true) {} |
| 25 | |
| 26 | ScopeGuard(ScopeGuard&& that) : f_(that.f_), active_(that.active_) { |
| 27 | that.active_ = false; |
| 28 | } |
| 29 | |
| 30 | ~ScopeGuard() { |
| 31 | if (active_) { |
| 32 | f_(); |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | void disable() { |
| 37 | active_ = false; |
| 38 | } |
| 39 | private: |
| 40 | F f_; |
| 41 | bool active_; |
| 42 | |
| 43 | ScopeGuard() = delete; |
| 44 | ScopeGuard(const ScopeGuard&) = delete; |
| 45 | ScopeGuard& operator=(const ScopeGuard&) = delete; |
| 46 | }; |
| 47 | |
| 48 | template<typename T> |
| 49 | ScopeGuard<T> create_scope_guard(T f) { |
| 50 | return ScopeGuard<T>(f); |
| 51 | } |
| 52 | |
| 53 | #endif // SCOPE_GUARD_H |