|
Boost : |
From: Greg Colvin (gcolvin_at_[hidden])
Date: 2001-07-20 12:33:43
From: Darin Adler <darin_at_[hidden]>
> On Tuesday, July 17, 2001, at 01:33 AM, Paul A. Bristow wrote:
>
> >>> 1 - const T mything( init_value );
> >>> // ...
> >>> T x = mything;
> >>
> >> The big disadvantage of the first way is that initialisation isn't
> >> guaranteed to happen soon enough if T has a nontrivial constructor. IMHO
> >> this is a showstopper, far more important than any aesthetic
> >> considerations.
> >
> > Can you explain to a naive C++ user if this is
> > a compiler implementation problem,
> >
> > or the way the user writes the constructor,
> >
> > or if it is fundamental to the language.
>
> It's fundamental to the language.
>
> > PS If the latter it would seem a showstopper for using C++! :-(
>
> It's a known flaw in the C++ language, but it's not a show-stopper for the
> entire language.
>
> Global objects in separate translation units (different source files,
> basically) aren't necessarily initialized in any particular order, so the
> constructor for one might run before or after the constructor for another.
> This makes it dangerous to use any code that uses a global object in code
> that might be called from the constructor of another global object. The
> standard way of avoiding this problem is to avoid these kinds of global
> objects and use one or another of the singleton approaches instead.
>
> One of the reasons this hasn't been fixed in the language is that there's
> no obvious rule that would work better. It's easy to define two global
> objects that each reference the other in their constructors. Which should
> be initialized first?
>
> There are some traditional solutions to this problem. The problem is
> mentioned in the "C++ FAQ Lite" document, which calls it the "static
> initialization order fiasco"
> <http://users.utu.fi/sisasa/oasis/cppfaq/ctors.html#[10.9]>, and in many,
> many other general C++ sources, so we ought not discuss it in detail on
> Boost unless there's a specific issue with a particular Boost library.
I notice that http://users.utu.fi/sisasa/oasis/cppfaq/ctors.html#[10.10]
recommends the following idiom:
Fred& x()
{
static Fred* ans = new Fred();
return *ans;
}
when I would have expected
Fred& x()
{
static Fred ans;
return ans;
}
or am I missing something (as usual)?
Anyway, a simple template for this idiom might be a useful addition to
Boost.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk