I’m currently working on a complex system in C++ that requires the initialization of a set of components, each potentially having a different number and type of parameters for their initialization and cleanup functions.
My goal is to structure this initialization process in such a way that:
- A series of initialization functions are called with specific parameters.
- Each function’s return code is checked, and upon success, the next function is called.
- If a function fails, the previously initialized components should be cleaned up.
I implemented an approach where, after each initialization function call, I manually checked the return value to decide whether to proceed with the next function or not. For the cleanup process, I stored the return codes and only called the corresponding cleanup functions if the recorded code was OK. While this method worked, it became increasingly difficult to maintain and understand as the system grew. The code quickly became cluttered and hard to follow, especially with more components and complex dependencies.
I’m wondering if there are more elegant methods, specific libraries, or modern C++ idioms that could simplify this task. Are there recommended practices for cleanly managing initialization and cleanup of resources with varying parameters?
M. Babe is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.