Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
util: Refactor the Defer class to a header to be reusable
Summary --- This commit adds a template class called `Defer` to the `util/` subdirectory. This class is designed to leverage RAII and execute a lambda at scope end. It is used by passing it a lambda (or `std::function`) at construction time which it will execute when the `Defer` instance is destructed. This class can be used as a language idiom to defer the execution of cleanup code at scope end -- even if an exception is thrown. Motivation: I noticed in various places in the codebase, very critical cleanup code is manually executed at scope end -- however if an exception is thrown by the code, the cleanup code will never run thus leading to `assert` failures or potential subtle bugs and resource leaks. What's worse, in some places the critical cleanup code is copy-pased in several places. Using this `Defer` idiom one can escape from all of this pain and also guarantee safety. This class was already used in this codebase in 2 places (added by me redundantly in both places, private to each translation unit in which it was added). In this commit we just refactor it out to a publicly-visible header in `util/defer.h` and thus we can re-use this idiom everywhere. Should this MR be accepted and merged, I do plan on using this idiom in the future in refactors and code cleanups or in new code. (I already know of 1 place where it should be added for safety.) Test Plan --- No semantic or other behavioral changes are introduced, however: - `ninja all check-all`
- Loading branch information