3

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?

6

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

cppreference.com - raii

This is the customary C++ technique to handle this issue.

  • Worth noting that it has been so since the 90s, and nowadays the standard library provides a lot of facilities that implement RAII, such as the smart pointers. – Marc.2377 Oct 25 '19 at 4:36
  • @DocBrown I learned to follow RAII when manually creating initialization functions for member variables. I'm not sure what case I'm missing. – candied_orange Oct 25 '19 at 14:32
  • @DocBrown I'll admit my use of smart pointers hasn't been extensive but I thought the point of them was to alleviate the need for naked pointers to a resource precisely so that a destructor will still be called when it goes out of scope, thus still following RAII. – candied_orange Oct 25 '19 at 20:02
  • @candied_orange: well, I guess it is better to delete my comments, they seem to be too nitty. There are probably cases where one has to think about a way for keeping track of the already allocated resources in a constructor, but I guess those case are the rare cases where one needs to implement a destructor manually. In modern C+, the needs for this are rare, indeed. – Doc Brown Oct 25 '19 at 22:09
  • 1
    @candied_orange: by "already allocated resources" I meant nothing but what the OP wrote in "all inits done before (which) must be cleaned up/de-init". Thinking twice, I guess my first comment was wrong, using smart pointers can probably handle all the cases I had in mind in an RAII style. It may, however, not fully obvious from the consise description you cited how to do this and how this counts as "RAII style" as well. This SO post contains some examples which might be helpful for the OP. – Doc Brown Oct 26 '19 at 6:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.