Boost logo

Boost :

From: Giovanni Piero Deretta (gpderetta_at_[hidden])
Date: 2008-01-15 10:19:34


On Jan 15, 2008 12:21 PM, Anthony Williams <anthony_w.geo_at_[hidden]> wrote:
> John Torjo <john.groups <at> torjo.com> writes:
>
> > Today starts the formal Fast-Track review of the Boost.Utility/Singleton
> > library. This is a very useful utility, so I'm expecting lots of reviews ;)
>
> > * What is your evaluation of the potential usefulness of the library?
>
> I don't think this is at all useful. People should not be encouraged to use
> singletons, as there is already a tendency towards overuse. In most
> circumstances, singletons are a poor design choice, so there is little
> requirement for their use.

I consider singletons just another form of globals and thus bad style.
But sometimes they get handy,
if you do not want to pass around a context to every function in a module.
Anyways, I've regretted too every single singleton that I have used.

What about a form of thread local singleton which can be replaced with
a scoped construct?

//global scope
singleton<my_object> my_singleton;

void foo() {
   my_singleton.instance().use_singleton(); // the globaly scoped one
or a local replacement.
}

void bar() {
  scoped_replacer _ (my_singleton); // replace my_object of baz with a copy
  my_singleton.instance().perform_local_modification();
  foo();
  // at this point my_object of baz is reinstantiated
}

void baz() {
  scoped_replacer _ (my_singleton, my_object()); // replace the
initial my_object

        // with a copy of the second parameter
  foo();
  // at this point the original my_object is reinstantiated
}

int main() {
  baz();
}

In practice it is a form of dynamic scoping, which might be more
useful and flexible than a static singleton.
You definitely want this dynamic scoped object to be per thread.

I haven't read Boost.Singleton documentation, maybe it already allows
such a functionality.

--
gpd

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk