Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing something to be destructed last in C++

Tags:

c++

destructor

I am working on a C++ app which internally has some controller objects that are created and destroyed regularly (using new). It is necessary that these controllers register themselves with another object (let's call it controllerSupervisor), and unregister themselves when they are destructed.

The problem I am now facing is happening when I quit the application: as order of destruction is not deterministic, it so happens that the single controllerSupervisor instance is destructed prior to (some) of the controllers themselves, and when they call the unregister method in their destructor, they do so upon an already destructed object.

The only idea I came up with so far (having a big cold, so this may not mean much) is not having the controllerSupervisor as a global variable on the stack, but rather on the heap (i.e. using new). However in that case I do not have a place to delete it (this is all in a 3rd party kind of library).

Any hints/suggestions on what possible options are would be appreciated.

like image 900
Steven Avatar asked Nov 13 '08 20:11

Steven


2 Answers

The order of destruction of automatic variables (that include "normal" local variables that you use in functions) is in the reverse order of their creation. So place the controllerSupervisor at the top.

Order of destruction of globals is also in the reverse of their creation, which in turn depends on the order in which they are defined: Later defined objects are created later. But beware: Objects defined in different .cpp files (translation units) are not guaranteed to created in any defined order.

I think you should consider using it how Mike recommended:

  1. Creation is done by using the singleton pattern (since initialization order of objects in different translation units are not defined) on first use, by returning a pointer to a function-static supervisor object.
  2. The supervisor is normally destructed (using the rules about destruction of statics in functions). controllers deregister using a static function of the supervisor. That one checks whether the supervisor is already destructed (checking a pointer for != 0). If it is, then nothing is done. Otherwise the supervisor is notified.

Since i imagine there could be a supervisor without a controller being connected (and if only temporary), a smart pointer could not be used to destruct the supervisor automatically.

like image 90
Johannes Schaub - litb Avatar answered Oct 08 '22 14:10

Johannes Schaub - litb


There is basically a whole chapter on this topic in Alexandrescu's Modern C++ Design (Chaper 6, Singletons). He defines a singleton class which can manage dependencies, even between singletons themselves.

The whole book is highly recommended too BTW.

like image 22
Alastair Avatar answered Oct 08 '22 12:10

Alastair