#include <SharedInstance.h>
Public Methods | |
SharedInstance () | |
~SharedInstance () | |
SHARED* | operator-> () |
const SHARED* | operator-> () const |
The SingletonDestroyer, an alternative approach, makes no guarantee as to what order or when the Single is destroyed. This becomes problematic when Singleton's refer to one another explicitly or implicitly through shared data. The Singleton can be deleted in an inappropriate order or at an unexpected time - freeing data still in use by another Singleton that has not been destroyed yet. This leads to access violations and in some cases memory leaks.
The ObjectLifetimeManager used in the ACE framework presents a much more controlled and complex solution. However, for small, simple applications that include co-dependent Singleton's, or short lived Singleton's this is a good solution.
@example This example demonstrates how to use this pattern to create a a single SocketPump object that will drive the low level i/o of a Socket implementation in a separate thread. The details of the i/o are left out for brevity.
class SocketImpl {
... SharedInstance<SocketPump> _pump;
public: SocketImpl(...) { _pump.register(this); } virtual ~SocketImpl(...) { _pump.unregister(this); } ... };
The SocketPump going to refer to the same SharedInstance for all SocketImpl objects. It will be destroyed when all the SocketImpl go out of scope. The SocketPump is automatically created & started and stopped & destroyed as necessary.
|
Update the shared instance count, instantiate the object if necessary |
|
Decrements the shared instance count, clean up the shared object if the count drops to 0 |
|
Provide access to the shared instance
|
|
Provide access to the shared instance
|