This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Initialization of a static member of a template class fails




John (Eljay) Love-Jensen schrieb:
Hi Valery,

I suspect your code is running into the dreaded Order Of Construction problem. Which is only turn-of-the-screw less painful than the even more dreaded Order Of Destruction problem.

I replaced this part of your code...

static instance_list s_instances;

...with a class function to access a function-wrapped static instance_list variable...

static instance_list& GetInstanceList()
{
  static instance_list s_instances;
  return s_instances;
}

...and the crasher (which I also saw) went away.

Of course, you won't want a class static accessor function wrapping an instance variable in a header file, since that may cause even harder to diagnose problems.  Such as:  every translation unit* getting one-or-more copies of an inlined GetInstanceList.  Doh!
The solution to that latter problem is rather heinous (in my opinion), which involves explicit instantiation for all known instances of Enum<T> in a designated translation unit.  Ugh.  Maybe there is a more elegant solution.

AFAIK, all this is solved implicitly by means of vague linking (aka COMDAT/linkonce support). Hence, putting GetInstanceList() in a header file is safe, it just has to be either in a template class or defined as inline. Of course, COMDAT support requires a half-decent linker, which IMHO is anyway a necessity for programming with C++.


In fact we use the "make it a template, then you never get multiple definition errors" trick frequently to instantiate things in a header file that have to be instantiated only once, but only if the header is actually included in one or more translation units.

Daniel



Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]