-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscoped_cleanup.h
64 lines (57 loc) · 1.94 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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 EASY_CURL__SCOPED_CLEANUP_H_
#define EASY_CURL__SCOPED_CLEANUP_H_
#include <utility>
// Run the given function body (which is typically a block of code surrounded by
// curly-braces) when the current scope exits.
//
// Example:
// int fd = open(...);
// SCOPED_CLEANUP({ close(fd); });
//
// NOTE: in the case that you want to cancel the cleanup, use the more verbose
// (non-macro) form below.
#define SCOPED_CLEANUP(func_body) \
auto VARNAME_LINENUM(scoped_cleanup) = MakeScopedCleanup([&] { func_body })
// A scoped object which runs a cleanup function when going out of scope. Can
// be used for scoped resource cleanup.
//
// Use 'MakeScopedCleanup()' below to instantiate.
template<typename F>
class ScopedCleanup {
public:
explicit ScopedCleanup(F f)
: cancelled_(false),
f_(std::move(f)) {
}
~ScopedCleanup() {
if (!cancelled_) {
f_();
}
}
void cancel() { cancelled_ = true; }
private:
bool cancelled_;
F f_;
};
// Creates a new scoped cleanup instance with the provided function.
template<typename F>
ScopedCleanup<F> MakeScopedCleanup(F f) {
return ScopedCleanup<F>(f);
}
#endif //EASY_CURL__SCOPED_CLEANUP_H_