2024-01-06 00:42:54 +08:00
|
|
|
// Copyright 2024 Memgraph Ltd.
|
2021-10-03 18:07:04 +08:00
|
|
|
//
|
|
|
|
// Use of this software is governed by the Business Source License
|
|
|
|
// included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source
|
|
|
|
// License, and you may not use this file except in compliance with the Business Source License.
|
|
|
|
//
|
|
|
|
// As of the Change Date specified in that file, in accordance with
|
|
|
|
// the Business Source License, use of this software will be governed
|
|
|
|
// by the Apache License, Version 2.0, included in the file
|
|
|
|
// licenses/APL.txt.
|
|
|
|
|
2017-08-11 15:32:46 +08:00
|
|
|
#pragma once
|
|
|
|
|
2024-01-06 00:42:54 +08:00
|
|
|
#include <concepts>
|
2017-08-11 15:32:46 +08:00
|
|
|
#include <functional>
|
|
|
|
|
2022-02-22 20:33:45 +08:00
|
|
|
namespace memgraph::utils {
|
2017-08-11 15:32:46 +08:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Calls a function in it's destructor (on scope exit).
|
|
|
|
*
|
|
|
|
* Example usage:
|
|
|
|
*
|
|
|
|
* void long_function() {
|
|
|
|
* resource.enable();
|
|
|
|
* // long block of code, might throw an exception
|
|
|
|
* resource.disable(); // we want this to happen for sure, and function end
|
|
|
|
* }
|
|
|
|
*
|
|
|
|
* Can be nicer and safer:
|
|
|
|
*
|
|
|
|
* void long_function() {
|
|
|
|
* resource.enable();
|
|
|
|
* OnScopeExit on_exit([&resource] { resource.disable(); });
|
2024-02-01 18:55:48 +08:00
|
|
|
* // long block of code, might throw an exception
|
2017-08-11 15:32:46 +08:00
|
|
|
* }
|
|
|
|
*/
|
2024-03-15 21:45:21 +08:00
|
|
|
template <std::invocable Callable>
|
2023-06-27 01:10:48 +08:00
|
|
|
class [[nodiscard]] OnScopeExit {
|
2017-08-11 15:32:46 +08:00
|
|
|
public:
|
2024-01-06 00:42:54 +08:00
|
|
|
template <typename U>
|
|
|
|
requires std::constructible_from<Callable, U>
|
|
|
|
explicit OnScopeExit(U &&function) : function_{std::forward<U>(function)}, doCall_{true} {}
|
2023-06-27 01:10:48 +08:00
|
|
|
OnScopeExit(OnScopeExit const &) = delete;
|
|
|
|
OnScopeExit(OnScopeExit &&) = delete;
|
|
|
|
OnScopeExit &operator=(OnScopeExit const &) = delete;
|
|
|
|
OnScopeExit &operator=(OnScopeExit &&) = delete;
|
|
|
|
~OnScopeExit() {
|
2024-03-15 21:45:21 +08:00
|
|
|
if (doCall_) std::invoke(std::move(function_));
|
2021-09-09 16:44:47 +08:00
|
|
|
}
|
|
|
|
|
2023-06-27 01:10:48 +08:00
|
|
|
void Disable() { doCall_ = false; }
|
|
|
|
|
2017-08-11 15:32:46 +08:00
|
|
|
private:
|
|
|
|
std::function<void()> function_;
|
2023-06-27 01:10:48 +08:00
|
|
|
bool doCall_;
|
2017-08-11 15:32:46 +08:00
|
|
|
};
|
2023-06-27 01:10:48 +08:00
|
|
|
template <typename Callable>
|
|
|
|
OnScopeExit(Callable &&) -> OnScopeExit<Callable>;
|
2022-02-22 20:33:45 +08:00
|
|
|
} // namespace memgraph::utils
|