A header-only, modern C++ and fast facility ScopeGuard that provide multiple usages which are simple and easy to use as other languages provide.
C++14 or later standard is required.
There're 3 ways to use ScopeGuard:
- Put the code executing when leaving current scope in code block finally{ }.
#include "ScopeGuard.h"
...
{
...
finally{
// callback statments
// such as releasing resources
};
...
} // callback statments are executed at this point
- put callable in INVOKE_ON_EXIT( )
...
{
void my_callback();
...
INVOKE_ON_EXIT(my_callback);
...
INVOKE_ON_EXIT([&] { /* releasing resources */ });
...
} // lambda and my_callback are invoked at this point
- using the make function MakeScopeGuard manually.
...
{
...
auto guard = sg::MakeScopeGuard(my_callback);
...
} // my_callback is invoked at this point
You could see the comments in ScopeGuard.h for more.