One of the most powerful expressions in C++ is the brace closing a scope. This is the place where destructors get called and the RAII magic happens. To tame this spell, you don't need to use smart pointers. All you need is an RAII guard – an object that, when constructed, will remember what it needs to do when destroyed. This way, regardless of whether the scope exits normally or by an exception, the work will happen automatically.
The best part – you don't even need to write an RAII guard from scratch. Well-tested implementation already exists in various libraries. If you're using GSL, which we mentioned in the previous chapter, you can use gsl::finally(). Consider the following example:
using namespace std::chrono; void self_measuring_function() { auto timestamp_begin = high_resolution_clock::now(); auto cleanup = gsl::finally([timestamp_begin] { auto timestamp_end = high_resolution_clock::now...