ScopeExit library provides an efficient and convenient way to execute statements when execution flow leaves current scope. It implements a so-called scope guard idiom and defines 3 type of guards:
SCOPE_EXIT
- statements are always executed on scope exitSCOPE_SUCCESS
- statements are executed on scope exit when no exceptions have been thrownSCOPE_FAILURE
- statements are executed when scope is leaving due to an exception
Using scope guards makes code much cleaner and allows to place resource allocation and clean up code next to each other. They also improve safety because cleanup code is always called independent of which paths are actually taken at runtime.
Scope guards are called in the reverse order they are defined.
- Easy to use
- Headers only
- Requires C++11 or higher
- No 3rd-party dependencies
- Cross-platform
- Minimal overhead (no std::function or virtual table)
- Clean code
- CMake integration
Here is a simple sample that prints htlm code. Scope exit blocks make sure that html tags are properly closed:
#include <iostream>
#include <ScopeExit/ScopeExit.h>
using namespace std;
int main()
{
cout << "<html>" << endl;
SCOPE_EXIT{ cout << "</html>" << endl; };
{
cout << "<head>" << endl;
SCOPE_EXIT{ cout << "</head>" << endl; };
cout << "<title>Hello</title>" << endl;
}
cout << "<body>" << endl;
SCOPE_EXIT{ cout << "</body>" << endl; };
cout << "<h1>Hello World!</h1>" << endl;
return 0;
}
More samples can be found in the samples folder.
ScopeExit is licensed under the MIT license. You can freely use it in your commercial or opensource software.
- Initial public release