CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jun 2002
    Location
    Sweden
    Posts
    81

    Statics in templates - a bug in VC?

    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:
    Code:
    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

  2. #2
    Join Date
    Jun 2002
    Location
    Sweden
    Posts
    81
    Ahem, the attachment...
    Attached Files Attached Files

  3. #3
    Join Date
    Aug 2000
    Location
    New Jersey
    Posts
    968
    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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured