There is an initialization function in my app that does multiple inits. What is a good way to keep a track of inits done so that if init
n fails all inits done before it must be cleaned up/de-init before exiting. Is there a good way this is usually handled?
Is there a good way this is usually handled?
Yes. It's called RAII.
Resource Acquisition Is Initialization or RAII can be summarized as follows:
- encapsulate each resource into a class, where
- the constructor acquires the resource and establishes all class invariants or throws an exception if that cannot be done,
- the destructor releases the resource and never throws exceptions;
- always use the resource via an instance of a RAII-class that either
- has automatic storage duration or temporary lifetime itself, or
- has lifetime that is bounded by the lifetime of an automatic or temporary object
This is the customary C++ technique to handle this issue.