Boost logo

Boost :

From: Eric Niebler (eric_at_[hidden])
Date: 2007-06-15 11:20:38

Giovanni Piero Deretta wrote:
> On 6/15/07, David Abrahams <dave_at_[hidden]> wrote:
>> [...]
>> I would put the reference itself in an unnamed namespace, and I'm pretty
>> sure that handles it. As long as the reference refers to something
>> not in an unnamed namespace:
>> template<typename T> struct static_const
>> {
>> static T const value;
>> };
>> template<typename T>
>> T const static_const<T>::value = {};
>> struct placeholder {};
>> namespace // <<============== HERE
>> {
>> placeholder const &_1 = static_const<placeholder>::value;
>> }
>> template<class T> void foo(T const &)
>> {
>> // use _1 here. OK, _1 refers to the same object
>> // in all translation units. It doesn't matter that the
>> // reference is has a different identity; the object is
>> // the same: static_const<placeholder>::value
>> }
> Instead of using a class statics, I've been using function static locals,
> the same trick used by the BOOST_PARAMETER_KEYWORD macro.
> What are the advantages and the disadvantages of the two aproach?

Function static locals are not initialized until a thread of execution
passes over their declaration. That means no static initialization, IIUC.

> Consider that I'm using the trick to name stateless function objects
> in header files
> These function objects sometime have a constructors, but I could
> easily make all of them POD if this would force the compiler to use
> static initialization.

'Fraid not. And the Boost.Parameter trick looks like this, IIRC:

   type const &name = get_static_local<type>();

Then this *really* doesn't do static initialization, because you're
calling a function.

> Anyways, why is it a necessity to have those objects statically
> initialized even if they are stateless?

If you are using the above formulation, then the reference is not
initialized until runtime. Due to order of initialization issues, you
could end up indirecting through an uninitialized reference and crash
even before you hit main().

I think BOOST_PARAMETER_KEYWORD is bad voodoo and should be changed, FWIW.

Eric Niebler
Boost Consulting
The Astoria Seminar ==>

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