Utilities
This page lists miscellaneous C++ utility types, functions and macros provided by cerlib.
defer
A defer block is used to perform an action at the end of a scope, no matter how the scope is exited. This is necessary for example when you deal with non-RAII types, i.e. types that have no destructors, or types that don’t manage their resources.
Take for example a pointer to some C object. You could write a wrapper class for such a resource that automatically manages its memory. However, sometimes you might need some ad-hoc RAII mechanism and don’t want to deal with writing wrappers.
This is especially true for when you deal with a specific C object only once.
In line 4, we set up a defer block that destroys the created handle.
Then we operate on this handle, where we expect exceptions to be thrown.
When line 10 (end of the scope) is reached, the defer block is executed
and someHandle
is therefore automatically destroyed.
With this mechanism, we can ensure that someHandle
is destroyed in every case.
defer_named
This is the same as defer, but able to be named. A named defer block is useful for when a planned action has to be cancellable.
For example, you’re planning to perform a specific action at the end of a scope in case of failure. You would then create a named defer block and only cancel it when your action succeeds.
In line 5, we set up a defer block named destroySomeHandle
.
Then we attempt to modify the handle, but the modifyHandle()
could throw an exception.
When an exception would be thrown, our function would automatically exit,
thereby calling our defer block.
Otherwise, if the modification was sucessful, we cancel the defer block (line 12), since we transfer
ownership of the handle to the Object
that is created and returned.
This will prevent the handle from being destroyed while it’s stored in the returned Object
.