I wrote a simplistic DBResourceMonitor class which is used by a set of database classes. When an instance of one of my database classes is created, it registers itself, and when destroyed, it unregisters itself with a singleton instance of DBResourceMonitor. When the application terminates, that global instance of DBResrouceMonitor is destroyed, which checks to make sure that there are no remaining registered instances of any of the classes that it monitors (i.e. that for every register, a unregister was called), and issues a TRACE output and ASSERT if there was a mismatch.
This is all well and good… until I put a couple of these database objects as members of my global application object. Hence, both the global application object, and the DBResourceMonitor are global singletons, and the application is the first to be constructed, hence the last to be destroyed, and hence when DBResrouceMonitor is destroyed, the members of the app object have yet to be unregistered, and so it throws an error indicating that there were mismatched register/unregister calls.
As far as I am aware, there is no way to ensure that the DBResrouceMonitor is constructed before the application object (and therefore destroyed afterwards).
Is this correct? Is there a clever way around that, or a way to rethink the above so that I can still track whether everything was taken care of before the final thread terminates?
Instead of having the objects register/deregister themselves with a singleton, you need to store the references to those objects in a collection property of the Singleton. So instead of doing:
you would use a factory pattern like:
and somewhere in DBResourceMonitor you could manage a collection of MyDBObjects