|
Boost : |
From: williamkempf_at_[hidden]
Date: 2001-08-06 09:11:44
--- In boost_at_y..., John Max Skaller <skaller_at_m...> wrote:
> williamkempf_at_h... wrote:
> [I'd even be worried about 'once' stuff: this seems
> like the moral equivalent of 'singletons' which I believe
> are also often symptomatic of a design error: is there a
> compelling example for it 'once' things?]
Once methods are not singletons. The classic reason for their need
is to synchronize the creation of global data. A simple example, I
wrote a gc_ptr<> class that had to track objects on the GC heap and
had a map to do so. In order to insure proper creation I followed
the standard idiom.
gc_map& get_map()
{
static gc_map map;
return map;
}
The above is not thread safe, however. The constructor for the
static "map" can be entered twice if get_map() is called from two
threads at (conceptually) the same time. Once methods allow us to
insure objects are created only once:
static gc_map* _map;
static boost::once_flag _map_once = BOOST_INIT_ONCE;
void init_map()
{
static gc_map map;
_map = map;
}
gc_map& get_map()
{
boost::call_once(&init_map, _map_once);
return *_map;
}
A better solution is for the compiler to handle this for us with the
advent of a new keyword:
gc_map& get_map()
{
static synch gc_map map;
return map;
}
This definately simplifies the code, but the result is the same.
Bill Kempf
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk