Boost logo

Boost :

From: Jonathan Wakely (cow_at_[hidden])
Date: 2005-01-20 06:10:13


On Wed, Jan 19, 2005 at 07:31:54PM +0100, Roland Schwarz wrote:

> Stefan Slapeta wrote:
>
> >I can ... a little static helper class is very helpful in this
> >situation (I posted it some time ago to the list):
> >
> >////////////////////////////////////////
> >// class template static_
> >////////////////////////////////////////
> >template <typename T, typename OwnerT = void>
> >struct static_
> >{
> > T* operator -> () const { return &member; }
> >
> > static T* get() { return &member; }
> >
> >private:
> > static T member;
> >};
> >
> >template <typename T, typename OwnerT> T static_<T, OwnerT>::member;
> >
> >///////////////
> >
> >
> >This way you can declare a global static instance of a type from
> >anywhere in the code, i.e. in header files, because templates show a
> >different behaviour for static members.
> >
> This is a really nice trick!
> However a question:
> Is it guaranteed by the standard, that the ctor of the "member" is
> beeing called at program startup?

No. Unless the member is instantiated it will not be initialised. Since
whether it is instantiated depends on whether you use it, which might
depend on whether you've got testing/loggin/debugging code turned on,
to guarantee that the member is initialised even when not used you might
have to explicitly instantiate it for each specilalisation:

template const int static_<int>::member = 0;
template const bool static_<bool>::member = true;

> Perhaps thread_specific_ptr itself should be implemented by means of
> this idiom then?

For that case it might not matter that the member isn't initialised
unless used, but if you're trying to guarantee some side-effect of its
construction always happens I think you need to explicitly instantiate.

jon

-- 
"That invisible hand of Adam Smith's seems to offer an extended middle 
 finger to an awful lot of people."
	- George Carlin

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