Skip to content

Instantly share code, notes, and snippets.

@RicoP
Created September 2, 2018 12:04
Show Gist options
  • Save RicoP/b639066a54e7b8bfdfddb56743d3dcc2 to your computer and use it in GitHub Desktop.
Save RicoP/b639066a54e7b8bfdfddb56743d3dcc2 to your computer and use it in GitHub Desktop.
defer macro
//from https://pastebin.com/3YvWQa5c
#define CONCAT_INTERNAL(x,y) x##y
#define CONCAT(x,y) CONCAT_INTERNAL(x,y)
template<typename T>
struct ExitScope {
T lambda;
ExitScope(T lambda):lambda(lambda){}
~ExitScope(){lambda();}
ExitScope(const ExitScope&);
private:
ExitScope& operator =(const ExitScope&);
};
class ExitScopeHelp {
public:
template<typename T>
ExitScope<T> operator+(T t){ return t;}
};
#define defer const auto& CONCAT(defer__, __LINE__) = ExitScopeHelp() + [&]()
//USE:
// auto tools_filename = malloc(42);
// defer { free(tools_filename); };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment