blob: d5a9235d1ab9c7ab406f4bde0c4814fd7196b53a [file] [log] [blame]
Elliott Hughes5beddb72014-09-04 16:09:25 -07001/*
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
Dmitriy Ivanovef1306d2014-09-08 16:22:22 -070017#ifndef _SCOPE_GUARD_H
18#define _SCOPE_GUARD_H
19
20#include "private/bionic_macros.h"
Elliott Hughes5beddb72014-09-04 16:09:25 -070021
22// TODO: include explicit std::move when it becomes available
23template<typename F>
24class ScopeGuard {
25 public:
26 ScopeGuard(F f) : f_(f), active_(true) {}
27
28 ScopeGuard(ScopeGuard&& that) : f_(that.f_), active_(that.active_) {
29 that.active_ = false;
30 }
31
32 ~ScopeGuard() {
33 if (active_) {
34 f_();
35 }
36 }
37
38 void disable() {
39 active_ = false;
40 }
41 private:
42 F f_;
43 bool active_;
44
Dmitriy Ivanovef1306d2014-09-08 16:22:22 -070045 DISALLOW_IMPLICIT_CONSTRUCTORS(ScopeGuard);
Elliott Hughes5beddb72014-09-04 16:09:25 -070046};
47
48template<typename T>
Dmitriy Ivanovef1306d2014-09-08 16:22:22 -070049ScopeGuard<T> make_scope_guard(T f) {
Elliott Hughes5beddb72014-09-04 16:09:25 -070050 return ScopeGuard<T>(f);
51}
52
Dmitriy Ivanovef1306d2014-09-08 16:22:22 -070053#endif // _SCOPE_GUARD_H