Skip to content

Instantly share code, notes, and snippets.

@win-t
Last active February 16, 2026 17:10
Show Gist options
  • Select an option

  • Save win-t/125f9e75c0a0f4a74a951478d27ccb4f to your computer and use it in GitHub Desktop.

Select an option

Save win-t/125f9e75c0a0f4a74a951478d27ccb4f to your computer and use it in GitHub Desktop.
C++ defer
#pragma once
#include <utility>
template <typename F>
struct DeferFinalizer final
{
F func;
DeferFinalizer(F &&f)
: func(std::forward<F>(f))
{
}
~DeferFinalizer()
{
func();
}
DeferFinalizer(const DeferFinalizer &) = delete;
DeferFinalizer &operator=(const DeferFinalizer &) = delete;
DeferFinalizer(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/cf1e4403781d57655904cf17fa2097d5a8230838/defer.h

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