2016-04-29 11:57:08 +00:00
|
|
|
#pragma once
|
2023-04-01 03:18:41 +00:00
|
|
|
///@file
|
2016-04-29 11:57:08 +00:00
|
|
|
|
2023-03-27 01:12:25 +00:00
|
|
|
/**
|
|
|
|
* A trivial class to run a function at the end of a scope.
|
|
|
|
*/
|
2021-12-30 23:50:23 +00:00
|
|
|
template<typename Fn>
|
2016-04-29 11:57:08 +00:00
|
|
|
class Finally
|
|
|
|
{
|
|
|
|
private:
|
2021-12-30 23:50:23 +00:00
|
|
|
Fn fun;
|
2024-03-10 06:05:50 +00:00
|
|
|
bool movedFrom = false;
|
2016-04-29 11:57:08 +00:00
|
|
|
|
|
|
|
public:
|
2021-12-30 23:50:23 +00:00
|
|
|
Finally(Fn fun) : fun(std::move(fun)) { }
|
2024-03-10 06:05:50 +00:00
|
|
|
// Copying Finallys is definitely not a good idea and will cause them to be
|
|
|
|
// called twice.
|
|
|
|
Finally(Finally &other) = delete;
|
|
|
|
Finally(Finally &&other) : fun(std::move(other.fun)) {
|
|
|
|
other.movedFrom = true;
|
|
|
|
}
|
2024-03-21 22:06:00 +00:00
|
|
|
~Finally() noexcept(false) { if (!movedFrom) fun(); }
|
2016-04-29 11:57:08 +00:00
|
|
|
};
|