finally.hh: delete copy constructor which is a bad idea

This commit is contained in:
Jade Lovelace 2024-02-26 01:21:54 -08:00
parent f6158ea53b
commit 76aced6915

View file

@ -11,8 +11,15 @@ class [[nodiscard("Finally values must be used")]] Finally
{ {
private: private:
Fn fun; Fn fun;
bool movedFrom = false;
public: public:
Finally(Fn fun) : fun(std::move(fun)) { } Finally(Fn fun) : fun(std::move(fun)) { }
~Finally() { fun(); } // 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;
}
~Finally() { if (!movedFrom) fun(); }
}; };