
Anthony Williams wrote:
Tobias Schwinger <tschwinger <at> isonews2.com> writes:
In fact, "just creating one" should be exactly what this library is all about .
Singleton is also called the Highlander pattern --- there can be only one.
Cool! I think I'll rename the library when it gets accepted :-P.
OK. With a Singleton, the type serves as the key to access the global which I personally find quite elegant.
and which I find to be the biggest problem with singletons.
I see. And it seems to me that you overrate the problem part of it.
A singleton can easily hold several instances of any other class, if a container is put into it.
Further you can use multiple-inheritance to instantiate many singletons with a common subobject at compile time.
So what are the alternatives (concrete interface proposals, please)?
One of the benefits you cite for your singleton design is the construction-on-demand, which ensures that things are always constructed when required. In that case, how about providing a class:
template<typename T> class construct_on_demand;
so you can create instances like:
construct_on_demand<Logger> myLogger;
and any call to myLogger->log() will ensure that the object is constructed before first use.
The appropriate operator-> call can also manage destruction order if required.
Interesting. Now let's see how we'd do it with Singletons: class Logger; struct myLogger : Logger, boost::singleton<myLogger> {}; // Please note that: // o We do not waste BSS space, and // o the instance can be allocated statically. OK, we use a type instead of the variable name. So what?!
What is the point of having more than one instance of a class that lives in static context -- and how would it be captured syntacticly? I can imagine a use for having lots of instances of boost::mutex at global scope --- each mutex protects a different thing. You don't need to capture the syntactic idea "there may be more than one of this class" --- that is the base level assumption.
Interestingly, you show us that in this very case the things you try to protect should be 'mutexed_singleton'S to avoid namespace pollution and to add clarity .
That was the first thought off the top of my head. It may be that a Locked<T> template (such as that mentioned by Phil Endecott) would be a good idea, but even then you've got multiple instances of the Locked<> template at global scope. My point is that just because something is a global doesn't mean you only want one instance of that *class*.
Yes, I do understand your point. I don't believe it is that important, however :-). Regards, Tobias