
Jason Kankiewicz wrote:
Regarding how a call to the singleton class' static "Instance()" method should be handled when no instance of the singleton exists
There is no instance method. I use smart pointers which always point to the same unique instance as the access mechanism: singleton_ptr < SingletonType, Name > ptr; ptr->SomeFunc ( ); // SomeFunc is a member function of type SingletonType
, couldn't the class take a "lifetime" policy class template parameter which determines whether a new instance is constructed or an exception should be thrown?
I am planning on providing multiple different pointer types to handle this so that different pointer types to the same instance can exist in the same program where needed. Specifically, the types I am considering are strong_ptr, lazy_ptr, weak_ptr, and zombie_ptr. The idea is that strong_ptr will create the instance if it does not already exist when the pointer is constructed, and will create it if needed when dereferenced as well. lazy_ptr will just create the instance if need be when dereferenced, and weak_ptr will never create the instance automatically. If the instance does not exist when the weak_ptr is dereferenced an exception will be thrown. I wanted zombie_ptr to be like a weak_ptr in that it never would attempt automatic instance creation, but when dereferenced instead of throwing an exception it would just do nothing and pretend that the call succeeded. I don't know how to allow this with pointer-to-member syntax, however, which is why I was considering adding the zombie_call method to the other pointer types. Rob Stewart wrote:
I am trying to come up with a mechanism which allows member functions of the singleton to be called if the instance exists, and which do nothing if the instance does not exist (no creation is attempted, the operation is simply skipped).
What is the use case for this?
Perhaps there is some sort of logging singleton that sends messages across a network or some other expensive-to-connect-to place. When the program is shutting down, there may be destructors that wish to log information, but not if doing so results in recreating an expensive singleton. Especially if there is a chance that construction of that singleton instance can throw an exception (like a failure to connect). A zombie_call method would be the perfect way to ensure that such messages are only logged when convenient. -Jason