Defer - DryPerspective/C_Builder_Extras GitHub Wiki
Header defer.h contains a macro DEFER which allows particular expression to be deferred and automatically executed at scope exit, regardless of whether the scope exits by return or exception. This can be useful in cases where some cleanup function must be called and the programmer does not wish to try to manually catch every possible error to call it and rethrow.
Note that due to the limitations of C++98, DEFER cannot capture any function-local variables when used on a C++98 compiler. It can only be used to execute stateless or globally available code. In the event that some function local object must be cleaned up, a RAII object such as a smart pointer is likely the superior choice. However, there is still a wide area of use for DEFER, especially when writing code which interfaces with C and which uses globally-available functions to perform cleanup.
As of C++17, defer does not have this restriction. It can safely and accurately capture local variables (by reference), meaning that tasks can be flexibly deferred without limit on their visibility.
It is strongly recommended that deferred code should not ever emit exceptions, as it may be executed during stack unwinding. In C++17, all deferred tasks are considered noexcept and the program will terminate if a deferred task throws an exception.
deferC++17 only
|
A class type which when provided with a callable and optionally a set of arguments will automatically invoke them on its own destruction |
| `DEFER(...) | A macro to automatically defer the enclosed expressions to be executed when the current scope exits |
#include "defer.h"
//Consider an old piece of code which uses globals to determine current program status
int current_setup_stage = 0;
bool is_processing = false;
int initialize_setup(){
is_processing = true;
//We want to make sure we don't accudentally leave is_processing true if we exit unexpectedly
DEFER(is_processing = false);
start_engines(); //May set current_setup_stage to another value
lights();
camera();
if(external_thing_available()){
action();
current_setup_stage = 10;
}
else{
throw my_exception("Setup failed");
}
}