aboutsummaryrefslogtreecommitdiff
path: root/include/cru/common/Guard.h
blob: 5a9f9c5d4395058ac2ed4b61483207ce153a70c8 (plain)
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
#pragma once

#include <functional>

namespace cru {
struct Guard {
  using ExitFunc = std::function<void()>;

  Guard() = default;
  explicit Guard(const ExitFunc& f) : on_exit(f) {}
  explicit Guard(ExitFunc&& f) : on_exit(std::move(f)) {}
  Guard(const Guard&) = delete;
  Guard(Guard&&) = default;
  Guard& operator=(const Guard&) = delete;
  Guard& operator=(Guard&&) = default;
  ~Guard() {
    if (on_exit) {
      on_exit();
    }
  }

  void Drop() { on_exit = {}; }

  ExitFunc on_exit;
};
}  // namespace cru