Coverage Report

Created: 2026-05-23 07:02

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/abseil-cpp/absl/cleanup/cleanup.h
Line
Count
Source
1
// Copyright 2021 The Abseil Authors.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//      https://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
//
15
// -----------------------------------------------------------------------------
16
// File: cleanup.h
17
// -----------------------------------------------------------------------------
18
//
19
// `absl::Cleanup` implements the scope guard idiom, invoking the contained
20
// callback's `operator()() &&` on scope exit.
21
//
22
// This class doesn't allocate or take any locks, and is safe to use in a signal
23
// handler. Of course the callback with which it is constructed also must be
24
// signal safe in order for this to be useful.
25
//
26
// Example:
27
//
28
// ```
29
//   absl::Status CopyGoodData(const char* source_path, const char* sink_path) {
30
//     FILE* source_file = fopen(source_path, "r");
31
//     if (source_file == nullptr) {
32
//       return absl::NotFoundError("No source file");  // No cleanups execute
33
//     }
34
//
35
//     // C++17 style cleanup using class template argument deduction
36
//     absl::Cleanup source_closer = [source_file] { fclose(source_file); };
37
//
38
//     FILE* sink_file = fopen(sink_path, "w");
39
//     if (sink_file == nullptr) {
40
//       return absl::NotFoundError("No sink file");  // First cleanup executes
41
//     }
42
//
43
//     // C++11 style cleanup using the factory function
44
//     auto sink_closer = absl::MakeCleanup([sink_file] { fclose(sink_file); });
45
//
46
//     Data data;
47
//     while (ReadData(source_file, &data)) {
48
//       if (!data.IsGood()) {
49
//         absl::Status result = absl::FailedPreconditionError("Read bad data");
50
//         return result;  // Both cleanups execute
51
//       }
52
//       SaveData(sink_file, &data);
53
//     }
54
//
55
//     return absl::OkStatus();  // Both cleanups execute
56
//   }
57
// ```
58
//
59
// Methods:
60
//
61
// `std::move(cleanup).Cancel()` will prevent the callback from executing.
62
//
63
// `std::move(cleanup).Invoke()` will execute the callback early, before
64
// destruction, and prevent the callback from executing in the destructor.
65
//
66
// Usage:
67
//
68
// `absl::Cleanup` is not an interface type. It is only intended to be used
69
// within the body of a function. It is not a value type and instead models a
70
// control flow construct. Check out `defer` in Golang for something similar.
71
72
#ifndef ABSL_CLEANUP_CLEANUP_H_
73
#define ABSL_CLEANUP_CLEANUP_H_
74
75
#include <utility>
76
77
#include "absl/base/config.h"
78
#include "absl/base/internal/hardening.h"
79
#include "absl/base/macros.h"
80
#include "absl/cleanup/internal/cleanup.h"
81
82
namespace absl {
83
ABSL_NAMESPACE_BEGIN
84
85
template <typename Arg, typename Callback = void()>
86
class [[nodiscard]] Cleanup final {
87
  static_assert(cleanup_internal::WasDeduced<Arg>(),
88
                "Explicit template parameters are not supported.");
89
90
  static_assert(cleanup_internal::ReturnsVoid<Callback>(),
91
                "Callbacks that return values are not supported.");
92
93
 public:
94
0
  Cleanup(Callback callback) : storage_(std::move(callback)) {}  // NOLINT
Unexecuted instantiation: log_sink_set.cc:absl::Cleanup<absl::cleanup_internal::Tag, absl::log_internal::(anonymous namespace)::GlobalLogSinkSet::LogToSinks(absl::LogEntry const&, absl::Span<absl::LogSink*>, bool)::{lambda()#1}>::Cleanup({lambda()#1})
Unexecuted instantiation: log_sink_set.cc:absl::Cleanup<absl::cleanup_internal::Tag, absl::log_internal::(anonymous namespace)::GlobalLogSinkSet::FlushLogSinks()::{lambda()#1}>::Cleanup({lambda()#1})
95
96
  Cleanup(Cleanup&& other) = default;
97
98
  void Cancel() && {
99
    absl::base_internal::HardeningAssert(storage_.IsCallbackEngaged());
100
    storage_.DestroyCallback();
101
  }
102
103
  void Invoke() && {
104
    absl::base_internal::HardeningAssert(storage_.IsCallbackEngaged());
105
    storage_.InvokeCallback();
106
    storage_.DestroyCallback();
107
  }
108
109
0
  ~Cleanup() {
110
0
    if (storage_.IsCallbackEngaged()) {
111
0
      storage_.InvokeCallback();
112
0
      storage_.DestroyCallback();
113
0
    }
114
0
  }
Unexecuted instantiation: log_sink_set.cc:absl::Cleanup<absl::cleanup_internal::Tag, absl::log_internal::(anonymous namespace)::GlobalLogSinkSet::LogToSinks(absl::LogEntry const&, absl::Span<absl::LogSink*>, bool)::{lambda()#1}>::~Cleanup()
Unexecuted instantiation: log_sink_set.cc:absl::Cleanup<absl::cleanup_internal::Tag, absl::log_internal::(anonymous namespace)::GlobalLogSinkSet::FlushLogSinks()::{lambda()#1}>::~Cleanup()
115
116
 private:
117
  cleanup_internal::Storage<Callback> storage_;
118
};
119
120
// `absl::Cleanup c = /* callback */;`
121
//
122
// C++17 type deduction API for creating an instance of `absl::Cleanup`
123
template <typename Callback>
124
Cleanup(Callback callback) -> Cleanup<cleanup_internal::Tag, Callback>;
125
126
// `auto c = absl::MakeCleanup(/* callback */);`
127
//
128
// C++11 type deduction API for creating an instance of `absl::Cleanup`
129
template <typename... Args, typename Callback>
130
0
absl::Cleanup<cleanup_internal::Tag, Callback> MakeCleanup(Callback callback) {
131
0
  static_assert(cleanup_internal::WasDeduced<cleanup_internal::Tag, Args...>(),
132
0
                "Explicit template parameters are not supported.");
133
134
0
  static_assert(cleanup_internal::ReturnsVoid<Callback>(),
135
0
                "Callbacks that return values are not supported.");
136
137
0
  return {std::move(callback)};
138
0
}
Unexecuted instantiation: log_sink_set.cc:absl::Cleanup<absl::cleanup_internal::Tag, absl::log_internal::(anonymous namespace)::GlobalLogSinkSet::LogToSinks(absl::LogEntry const&, absl::Span<absl::LogSink*>, bool)::{lambda()#1}> absl::MakeCleanup<, absl::log_internal::(anonymous namespace)::GlobalLogSinkSet::LogToSinks(absl::LogEntry const&, absl::Span<absl::LogSink*>, bool)::{lambda()#1}>(absl::cleanup_internal::Tag)
Unexecuted instantiation: log_sink_set.cc:absl::Cleanup<absl::cleanup_internal::Tag, absl::log_internal::(anonymous namespace)::GlobalLogSinkSet::FlushLogSinks()::{lambda()#1}> absl::MakeCleanup<, absl::log_internal::(anonymous namespace)::GlobalLogSinkSet::FlushLogSinks()::{lambda()#1}>(absl::cleanup_internal::Tag)
139
140
ABSL_NAMESPACE_END
141
}  // namespace absl
142
143
#endif  // ABSL_CLEANUP_CLEANUP_H_