Half a singleton
538
0
Advertisement
One thing I've noticed about singletons in C++ is that they're usually used to solve two related problems: the one only one object of a class problem and the order of initialization problem. Of the two, the order of initialization problem is probably more significant, but rarely gets any fanfare. This usually comes up in static member variables of classes, which are essentially glorified global variables living in a class's scope.
For example, the master lock I described a couple of entries ago is an example of such a pseudo-singleton. It has all the scaffolding associated with a singleton, except for the one object per class part. There is only one master lock object, but it other mutexes may be spawned in the program freely. One approach to this is a generalization of the Singleton scheme.
Prepackaged C++ Singleton implementations are currently usually done as template classes parameterized on the singleton's class type. Such classes have declarations that often look like: template class Singleton. If you generalize this to template class Singleton then with some types T, you can use this kind of template to address the initialization order of "static" class variables.
This can be extended to different components used by singleton templates. For example, I now use this guy in my code library:
It's as ugly as sin, but can be used as a backend for more full blown singleton solutions, to wrap the creation/destruction and access to the data. For example, this class backs the master lock I described earlier, as well as my ClassLevelLockable<> class, all of which use CreateStatic<> with T = Mutex, but different Key types.
For example, the master lock I described a couple of entries ago is an example of such a pseudo-singleton. It has all the scaffolding associated with a singleton, except for the one object per class part. There is only one master lock object, but it other mutexes may be spawned in the program freely. One approach to this is a generalization of the Singleton scheme.
Prepackaged C++ Singleton implementations are currently usually done as template classes parameterized on the singleton's class type. Such classes have declarations that often look like: template class Singleton. If you generalize this to template class Singleton then with some types T, you can use this kind of template to address the initialization order of "static" class variables.
This can be extended to different components used by singleton templates. For example, I now use this guy in my code library:
|
It's as ugly as sin, but can be used as a backend for more full blown singleton solutions, to wrap the creation/destruction and access to the data. For example, this class backs the master lock I described earlier, as well as my ClassLevelLockable<> class, all of which use CreateStatic<> with T = Mutex, but different Key types.
Advertisement
Advertisement
Advertisement
Discussion