Skip to content

Instantly share code, notes, and snippets.

@win-t
Created May 3, 2020 10:27
Show Gist options
  • Save win-t/125f9e75c0a0f4a74a951478d27ccb4f to your computer and use it in GitHub Desktop.
Save win-t/125f9e75c0a0f4a74a951478d27ccb4f to your computer and use it in GitHub Desktop.
C++ defer
#pragma once
template<typename F>
class DeferFinalizer final {
F func;
bool moved;
public:
DeferFinalizer(F&& f)
: func(std::forward<F>(f))
, moved(false)
{ }
DeferFinalizer(DeferFinalizer&& other)
: func(std::move(other.func))
, moved(other.moved)
{
other.moved = true;
}
~DeferFinalizer() {
if(!moved) func();
}
DeferFinalizer(const DeferFinalizer&) = delete;
DeferFinalizer& operator=(const DeferFinalizer&) = delete;
DeferFinalizer& operator=(DeferFinalizer&&) = delete;
};
struct {
template<typename F>
DeferFinalizer<F> operator<<(F&& f) {
return DeferFinalizer<F>(std::forward<F>(f));
}
} deferrer;
#define TOKENPASTE(x, y) x ## y
#define TOKENPASTE2(x, y) TOKENPASTE(x, y)
#define defer auto TOKENPASTE2(__deferred_lambda_call, __COUNTER__) = deferrer << [&]
@win-t
Copy link
Author

win-t commented May 3, 2020

this snippet is copied from here
to make it downloadable

just

wget https://gist.githubusercontent.com/win-t/125f9e75c0a0f4a74a951478d27ccb4f/raw/ff555964b6baf69acbe2c939b50916e70c1b02a8/defer.h

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment