Boost logo

Boost :

From: Jorge Lodos (lodos_at_[hidden])
Date: 2005-02-15 13:22:38


> -----Original Message-----
> From: boost-bounces_at_[hidden] [mailto:boost-bounces_at_[hidden]]
> On Behalf Of Peter Dimov
> Sent: Monday, February 14, 2005 4:27 PM
> To: boost_at_[hidden]
> Subject: Re: [boost] singleton usage
>
> Jorge Lodos wrote:
> >
> > Thank you for your comments. I agree with everything you said and try
> > to avoid singletons in the first place. However, I have a practical
> > problem
> > that I have been able to "solve" only thru singletons.
> > In a header only library that uses a class factory, the registration
> > of objects with the factory is performed in a constructor of an
> > object inside
> > an anonymous namespace. Since the header may be #included more that
> > once, I made those objects singletons to avoid multiple registration.
> > The singleton::instance method may be called more that once without
> > need, that's why I put "solve" in quotes. Since the object is inside
> > an anonymous namespace, I can not use templates, which never get
> > instantiated.
> > If you or anyone else have a suggestion that allows for automatic
> > registration without using singletons please share it :-)
>
> Can you use something like the following:
>
> class auto_reg
> {
> static int count_;
>
> auto_reg()
> {
> if( ++count_ == 1 ) register();
> }
>
> ~auto_reg()
> {
> if( --count_ == 0 ) unregister();
> }
> };
>
> int auto_reg::count_;
>
> To make it header-only use the template<class _ = void> trick.
>

Well, this sure would replace the singletons, thanks! Still, the class
constructor will be called more than once. I was hoping there was a solution
where this wouldn't happen. Some template magic, I guess :-).
Thanks again!

Jorge

Jorge


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