Link to home
Start Free TrialLog in
Avatar of Man9283
Man9283

asked on

How to create a Singleton parent class

I'm trying to create a Singleton parent class that I can reuse every time I need a singleton.

But I'm having several problems.
First, when I make the destructor protected, VC++ 6.0, fails to compile it.

class Singleton
{
protected:
 ~Singleton();
   Singleton();
  //copy constructor and assignment constructor here ****
public
  static Singleton* GetInstance(){static Singleton s; return &s;}
};

I don't see why this doesn't compile.

I'm also not sure if I should make Singleton a virtual class or a template class.

Does any one have some example code for a Singleton parent class?

Any advise as to what would be better (virtual or template)?

And how can I get the compiler to compile a class that has a protected or private distructor?
Avatar of Axter
Axter
Flag of United States of America image

I recommend you use a template class over virtual class.
The down side with a template class is that you have to put all the code in the header.
That shouldn't be a problem, because there shouldn't be too much code involved in such a class.
ASKER CERTIFIED SOLUTION
Avatar of Axter
Axter
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of GaryFx
GaryFx

Use the SingletonHolder mechanism in Loki.  While you're at it, pick up a copy of Alexandrescu's book, Modern C++ Design.  There are a lot of other issues related to the proper destruction.

Loki/Modern C++/Alexandrescu home page: http://moderncppdesign.com
Visual C++ 6.0 port:    http://fara.cs.uni-potsdam.de/~kaufmann/?page=lokiport (though I don't know how well it handles Singletons).
Loki project page: http://sourceforge.net/projects/loki-lib/

Gary
Avatar of Man9283

ASKER

GaryFx,
I downloaded and tried out the code, but it has way too much over head, and I had to comment out some of the code just to get it to compile.
I had to comment out 4 lines of code.  Two of which involved macros (#define).

I always try to avoid adding macros to my code, especially in the headers.

Thanks any way, but I'm going with Axter's code.

Axter,
Thanks, that works great.