Boost logo

Boost :

Subject: Re: [boost] Is there any interest in a base class which prevents construction during the static initialization phase?
From: Ben Robinson (icaretaker_at_[hidden])
Date: 2011-06-14 00:28:26

> On Jun 12, 2011, at 4:51 PM, Ben Robinson wrote:
> > Because the order of static initialization is undefined, numerous
> > difficult
> > to detect problems can arise when multiple objects are initialized
> > during
> > the static initialization phase. This base class would guarantee
> > that a
> > class will never be unintentionally constructed during static
> > initialization. This is the same philosophy behind how
> > boost::noncopyable
> > guarantees that a class will never be unintentionally copied.
> >
> > int main()
> > {
> > nonstaticinitializable::enable_initialization(); // Indicates that
> > static initialization is complete.
> > Foo foo; // This instance initializes successfully after static
> > initialization.
> > return 0;
> > } // main
> >
> > What does Boost think about submission::nonstaticinitializable (I
> > chose the
> > name to mirror noncopyable)?
> The requirement to modify main() is sufficiently burdensome that I
> probably wouldn't use this technique, though I admit the failure mode
> is an assertion failure that's easy to fix. But also consider that
> the unit defining main() might be written in C.
> Josh


The requirement is that a single call to a static function is made as the
first line of executable C++ code, in order to define the boundary between
static initialization, and run-time. Usually this is in main(), but it can
be elsewhere. Only a single function call is required, even if every single
class in the executable load module inherits from it. I also didn't point
out that there is zero performance hit in a release build, as asserts become
a noop and the empty base class constructor is inlined out. Also, no vtable
is introduced, and a total of only one bool of memory is consumed for the
entire program, independent of how many classes use it.

I believe the time saved by avoiding debugging static initialization order
problems greatly outweighs the cost of adding a single function call to
the program. The philosophy is the same as for boost::noncopyable, express
your intent to the compiler/program, so you don't accidentally use a class
in an unintended way. It is preferable to catch these kinds of problems
earlier, rather than later. This class is designed to be of general
utility, and I intend to make it standard practice for my applications, just
how I already inherit from noncopyable as standard practice, unless I
specifically need otherwise.

Thank you,

Ben Robinson

Boost list run by bdawes at, gregod at, cpdaniel at, john at