
On 6/15/07, Eric Niebler <eric@boost-consulting.com> wrote:
Giovanni Piero Deretta wrote:
On 6/15/07, David Abrahams <dave@boost-consulting.com> 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.
IIRC there are some cases where even function static locals are guaranteed to be still initialized statically, but I do not remember exactly in what cases (probably pods initialized with constants), anyways, your observation below makes this useless in my case.
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>();
That exactly what I'm doing.
Then this *really* doesn't do static initialization, because you're calling a function.
You are definitely right.
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 feared something like that. I'll change my code to use a class template static. Hopfully most of the usages are protected by a macro and I only need to change that.
I think BOOST_PARAMETER_KEYWORD is bad voodoo and should be changed, FWIW.
thanks! gpd