2022-02-22 20:33:45 +08:00
|
|
|
// Copyright 2022 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
|
|
|
|
|
|
|
|
#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(); });
|
|
|
|
* // long block of code, might trow an exception
|
|
|
|
* }
|
|
|
|
*/
|
|
|
|
class OnScopeExit {
|
|
|
|
public:
|
2021-02-18 22:32:43 +08:00
|
|
|
explicit OnScopeExit(const std::function<void()> &function) : function_(function) {}
|
2017-08-11 15:32:46 +08:00
|
|
|
~OnScopeExit() { function_(); }
|
|
|
|
|
2021-09-09 16:44:47 +08:00
|
|
|
void Disable() {
|
|
|
|
function_ = [] {};
|
|
|
|
}
|
|
|
|
|
2017-08-11 15:32:46 +08:00
|
|
|
private:
|
|
|
|
std::function<void()> function_;
|
|
|
|
};
|
2018-04-22 14:31:09 +08:00
|
|
|
|
2022-02-22 20:33:45 +08:00
|
|
|
} // namespace memgraph::utils
|