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.
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:
!= 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With