1/**
2 * Copyright 2021 Alibaba, Inc. and its affiliates. All Rights Reserved.
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 * \author Haichao.chc
17 * \date Nov 2020
18 * \brief Scope guard like golang defer
19 */
20
21#pragma once
22
23#include <functional>
24#include <vector>
25
26namespace proxima {
27namespace be {
28
29/*
30 * RAII style scope guard to ensure release resource
31 */
32class Defer {
33 public:
34 using Func = std::function<void(void)>;
35
36 Defer() = default;
37
38 Defer(Func f) {
39 funcs_.emplace_back(f);
40 }
41
42 Defer(const Defer &) = delete;
43
44 Defer &operator=(const Defer &) = delete;
45
46 ~Defer() {
47 for (auto func : funcs_) {
48 func();
49 }
50
51 funcs_.clear();
52 }
53
54 public:
55 void operator()(Func f) {
56 funcs_.emplace_back(f);
57 }
58
59 private:
60 std::vector<Func> funcs_;
61};
62
63} // namespace be
64} // end namespace proxima
65