I was first introduced to the concept of defer while playing with languages like Go and Zig. Wouldn't it be cool to implement something like this in C/C++?
While trying to learn about manual memory management, I landed on this amazing blog series called "Memory Allocation Strategies" by Ginger Bill. So while checking other blog article from the site I found the article "A Defer Statement For C++11" where I found a C++ implementation for defer.
template <typename F> struct privDefer { F f; privDefer(F f) : f(f) {} ~privDefer() { f(); } }; template <typename F> privDefer<F> defer_func(F f) { return privDefer<F>(f); } #define DEFER_1(a, b) a##b #define DEFER_2(a, b) DEFER_1(a, b) #define DEFER_3(a) DEFER_2(a, __COUNTER__) #define defer(code) auto DEFER_3(_defer_) = defer_func([&](){code;})
Simply put, you just wrap the function call with a lambda expression (C++11) and pass it as an agrument to the defer_func. This function returns an object of type privDefer, and as the scope ends the destructor calls the lambda expression that has been passed.