This repository has been archived by the owner on Jul 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 238
/
Copy pathscoped_cleanup.h
executable file
·80 lines (69 loc) · 2.31 KB
/
scoped_cleanup.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef UTIL_SCOPED_CLEANUP_H_
#define UTIL_SCOPED_CLEANUP_H_
#include <functional>
#include <type_traits>
#include "base/macros.h"
namespace util {
// A scoped cleanup action that is performed on destruction. The action can be
// cancelled by calling Cancel().
//
// This can take any sort of callable argument including functors, function
// pointers, member-function pointers (const or not), and lambdas.
//
// If you are trying to do RAII-style resource management, consider UniqueValue
// instead, which builds on top of ScopedCleanup.
//
// Examples:
//
// // Functor arg.
// ScopedCleanup bing{CloseFileFunctor(fd)};
//
// // Function arg.
// ScopedCleanup bang{::abort};
// ScopedCleanup bong{::close, fd};
//
// // Member function arg.
// ScopedCleanup boom{&Database::Reset, &db};
// ScopedCleanup boing{&Database::Close, &db, fd};
//
// // Lambda arg.
// ScopedCleanup bump{[fd]() { ::close(fd); }};
//
// This class is thread-compatible.
class ScopedCleanup {
public:
// Makes a ScopedCleanup from a callback function. The args parameters are
// copied and bound to the function; the result must be a nullary function.
template<typename T, typename... Args>
explicit ScopedCleanup(T callable, const Args&... args)
: active_(true), cleanup_(::std::bind(callable, args...)) {}
virtual ~ScopedCleanup() {
if (active_) {
cleanup_();
}
}
// Cancels a ScopedCleanup. Once called, this cleanup action will not run.
void Cancel() {
active_ = false;
}
private:
// The actual cleanup object. Cleanup is triggered by destruction.
bool active_;
::std::function<void()> cleanup_;
DISALLOW_COPY_AND_ASSIGN(ScopedCleanup);
};
} // namespace util
#endif // UTIL_SCOPED_CLEANUP_H_