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 ANDROID_BASE_SCOPEGUARD_H 18#define ANDROID_BASE_SCOPEGUARD_H 19 20#include <utility> // for std::move 21 22namespace android { 23namespace base { 24 25template <typename F> 26class ScopeGuard { 27 public: 28 ScopeGuard(F f) : f_(f), active_(true) {} 29 30 ScopeGuard(ScopeGuard&& that) : f_(std::move(that.f_)), active_(that.active_) { 31 that.active_ = false; 32 } 33 34 ~ScopeGuard() { 35 if (active_) f_(); 36 } 37 38 ScopeGuard() = delete; 39 ScopeGuard(const ScopeGuard&) = delete; 40 void operator=(const ScopeGuard&) = delete; 41 void operator=(ScopeGuard&& that) = delete; 42 43 void Disable() { active_ = false; } 44 45 bool active() const { return active_; } 46 47 private: 48 F f_; 49 bool active_; 50}; 51 52template <typename T> 53ScopeGuard<T> make_scope_guard(T f) { 54 return ScopeGuard<T>(f); 55} 56 57} // namespace base 58} // namespace android 59 60#endif // ANDROID_BASE_SCOPEGUARD_H 61