Last active
December 23, 2015 04:09
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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