Skip to content

Instantly share code, notes, and snippets.

@jorgenpt
Last active December 23, 2015 04:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jorgenpt/6577922 to your computer and use it in GitHub Desktop.
Save jorgenpt/6577922 to your computer and use it in GitHub Desktop.
Automatically `delete' a variable at end of scope. From https://twitter.com/Jonathan_Blow/status/379394775788425216
template <typename T>
struct Scope_Delete_Handler
{
T target;
Scope_Delete_Handler(T _target) :target(_target) {}
~Scope_Delete_Handler() { delete target; }
};
#define Scope_Delete(x) Scope_Delete_Handler <decltype(x)> _##x##_## __LINE__(x)
/* Usage: */
bool foo()
{
SomeType *bar = new SomeType();
Scope_Delete(bar);
/* .. Do things with bar and be sure that it's deleted even if you exit early .. */
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment