Click to See Complete Forum and Search --> : Statics in templates - a bug in VC?


amag
September 12th, 2002, 05:07 AM
My problem is that I have a template-based factory. The idea is that classes plug themselves in. To be able to do this the factory is a singleton and you access the one instance through an instance()-method.
Initially my instance()-method looked something like this:

generic_factory<ProdType, ClassID> &instance()
{
static generic_factory<ProdType, ClassID> self;
return self;
}

But that didn't work when I compiled it in release-mode (worked alright in debug-mode and in GCC though).

Now I have a static auto_ptr to the instance in the class body instead. Since the class is a template the auto_ptr must be initialised in the header that contains the factory (this would cause a linker-error if the class wasn't a template).
My problem is now that the factory is created more than once (and I guess it depends on the above paragraph), so some classes that register may be lost.
Which classes get lost seems to depend on the compilation order, but I can't see how my class-hierarchy is dependant on the order of static initialisations across translation-units.

I also wrote a similar class-hierarchy (for debugging) where I instatiated the template with a builtin type (int) and everything worked as it should. When I instantiated it with a type of my own (a class) it exhibited the same problem as the factory.

I've attached a workspace that exhibits the problem (includes all the relevant source-files).

I'm sorry for the long and incoherent post, but it isn't easy to explain this.

/Andreas

amag
September 12th, 2002, 05:10 AM
Ahem, the attachment...

Axter
September 13th, 2002, 05:17 AM
This is not a bug in VC.
You're having this problem because your static factory function is part of a template class.
When a template class has a static function, it will have an instance of that static function for every template type used with that class.

To fix your problem, you either need to put your instance() function on a non-template base class, or make it a global function.