Skip to content

Instantly share code, notes, and snippets.

@stevemk14ebr
Created January 8, 2021 05:02
Show Gist options
  • Save stevemk14ebr/b087a996c4225ad2be07297f03e6ba7c to your computer and use it in GitHub Desktop.
Save stevemk14ebr/b087a996c4225ad2be07297f03e6ba7c to your computer and use it in GitHub Desktop.
GoLang's defer in C++
template<typename Func>
class imp_defer_obj {
public:
imp_defer_obj(Func f) : FinalActionFunc(f) {}
~imp_defer_obj() {
FinalActionFunc();
}
private:
Func FinalActionFunc;
};
template <typename F>
static inline imp_defer_obj<F> imp_defer(F f) {
return imp_defer_obj<F>(f);
}
#define PP_CAT(a, b) PP_CAT_I(a, b)
#define PP_CAT_I(a, b) PP_CAT_II(~, a ## b)
#define PP_CAT_II(p, res) res
#define UNIQUE_NAME(base) PP_CAT(base, __COUNTER__)
#define defer(x) auto UNIQUE_NAME(finally_obj) = imp_defer([&]() { \
x;\
})
/*
Example:
#include "defer.hpp"
int main() {
char* tmp = new char[256];
defer(if(tmp != nullptr) {
delete[] tmp;
});
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment