Click to See Complete Forum and Search --> : Singleton Class


rudyloo
April 4th, 2008, 07:35 AM
Hi,

I heard the term Singleton for the first time yesterday.. and after reading around on the net setup a singleton class for my program.

It might be a stupid question, but i am a little confused.

All the code is in the .h file Dont we need a .ccp file?

It is working right now, but i dont want to put large methods and stuff in teh header file.

Does anyone know any good clear examples of singleton usage?

I looked at:
http://sourcemaking.com/design_patterns/singleton/c++/1
http://bytes.com/forum/thread656124.html

Thanks

Lindley
April 4th, 2008, 07:40 AM
Writing code in the h file is fine, so long as you don't need the #including cpp file to compile in a hurry. The benefit of writing your class functions in a separate cpp file is that it reduces compile time by handing off some responsibility to the linker.

The only time you *must* write code in an h file (or #include the .cpp file at the end of the h file, at least) is if you're using templates. I really hate that, but there it is.

As for singletons, the only thing that distinguishes them from other classes is that the constructors and assignment operators are private, and the only way to get the object is by using getInstance().

rudyloo
April 4th, 2008, 07:58 AM
Thanks

Do you know any good links to examples with good style etc.?

Hmm.. I just noticed I get memory leaks when using getInstance();

Lindley
April 4th, 2008, 08:09 AM
There are two schools of thought about that. One says you should either declare your instance static (rather than allocating it with new on the first getInstance()), or else write a destroyInstance() function; in this way you avoid the memory leak.

The other says that memory "leaks" which can only ever happen once in a program are irrelevant.

Richard.J
April 4th, 2008, 10:27 AM
in this thread we had a discussion of singletons just recently:
http://www.codeguru.com/forum/showthread.php?t=448834