Need "simple" singleton class example

Started by
32 comments, last by johnnyBravo 20 years, 5 months ago
quote:Original post by baskuenen
class CBla{public:  CBla()  {    assert(pBla == NULL);  //this is a singleton!    pBla = this;  }  ~CBla()  {    pBla = NULL;  }};CBla *pBla = NULL;    //global var



Heh, this is a lot of things, but it certainly isnt a singleton
in any shape or form.

A singleton is a class which can only have one instance, that has a global point of access to it.

The global point of access is where the simularities between your .. ''thing'' and a singleton end. Whats stopping someone from doing this..

CBla first_instance;CBla second_instance;CBla third_instance; 





Advertisement
Eek.. must be spreading

That should be

CBla first_instance;CBla second_instance(first_instance);CBla third_instance(first_instance); 


I.e. using the implicitly declared copy constructor
quote:But i just realised i may need more than one of the same class to store varying data. Is there a way to do this while still being able to call the class from anywhere and use it anywhere?

You don't want a singleton then. Singletons enforce a single instance of a class that is accessible anywhere.

I don't really see the point of a simple singleton class, either, it is just a class with ctor/dtor private and a method called instance() that returns a reference. Loki's Singleton wrapper is meaningful because he at least has templated policy classes that can make the singleton thread-safe and other cool things. The author of that is brilliant.

(singleton tirade)
Resist the urge to use globals/singletons until you have no other options. Your back should be to the wall (proverbially) and it should be very clear that you need a single instance, plus global accessibility (e.g. clients shouldn't have to concern themselves with providing the information for elegance).

Singletons do rock in that a Meyers singleton won't be instantiated unless it is actually needed. To get around lifetime issues, I use a LifetimeManager that manages the dependencies, I recommend people do the same if its possible for singletons to be dependent on one another.

Just because a singleton is a design pattern doesn't mean it should be everywhere. Just because you need only one instance of a class doesn't mean it should be a singleton. I see in a bunch of articles where people make stuff singletons, and have to ask why. Fighting with initialization/destruction order sucks. Enforcing singletons in an application spread across DLLs forces you to fight either DLL memory boundaries or be dependent on the runtime library being linked in at runtime, and therefore present on the user's system.

Singletons seem like a hack to support something that C++ has trouble expressing 'natively.' I cannot think of a better way to do it than we have right now. Issues with separate heaps/runtime libraries make things far more difficult than they need to be.

[edited by - antareus on November 9, 2003 2:55:36 PM]
--God has paid us the intolerable compliment of loving us, in the deepest, most tragic, most inexorable sense.- C.S. Lewis
quote:Original post by Anonymous Poster
Eek.. must be spreading

That should be

CBla first_instance;CBla second_instance(first_instance);CBla third_instance(first_instance);  


I.e. using the implicitly declared copy constructor


Well, good point. I would hope logic prevents any user doing anything like that
Without viewing all of the current possibilities in singleton creation (in this thread and otherwise), I could solve it by adding a private copy-constructor and =operator.

But I''m still putting my hope into an extremely good logical design of all my classes, instead of building singletons.

You''re probably thinking what a lame answer this is.
But my concern is.. when I start coding complete singletons and other ''design-technical'' stuff... where does it end?!
For example: a portable typeid-class where all other classes are derived from. Or maybe something with streaming files/memory/sockets/input/... (like delphi does more or less).
Streaming in and out all variables from any class.. maybe very nice, but if my teammates saw me do that.. it''ll not improve my popularity

One small advantage to my hacked singleton is that I control when this class gets con- and de-structed. So far this has proven to be very welcome!


I guess when choosing how to implement your singleton class, it''s also a matter of taste.
quote:
Resist the urge to use globals/singletons until you have no other options. Your back should be to the wall (proverbially) and it should be very clear that you need a single instance, plus global accessibility (e.g. clients shouldn't have to concern themselves with providing the information for elegance).

I totally agree with you. Once newbies learn about singeltons they start using them for everything when their not needed (I used to do that all the time). And if you have to use a singelton, don't use the global reference, pass it to the function/class. ie, don't do this:
class Singelton{...};void doStuff(){    singelton::get().doStuff();}int main(){   doStuff();   return 0;}  

do this:
class Singelton{...};void doStuff(Singelton& s){    s.doStuff();}int main(){   doStuff(Singelton::get());   return 0;}  


[edited by - brassfish89 on November 9, 2003 6:35:02 PM]
About these design patterns, use them to solve a problem that otherwise would be hard to understand and maintain. Granted, some of the patterns are just everyday things like references, etc. but stuff like state pattern or task manager, etc. really do help make order out of an otherwise spaghetti code.
Ehh... the guy asked for a SIMPLE singleton class example.

MyClass.h:

class MyClass{public	MyClass();	~MyClass();	void MyTestFunction();	static MyClass* singleton;};


MyClass.cpp

#include "MyClass.h"MyClass *MyClass::singleton = NULL;MyClass::MyClass{	singleton = this;}MyClass::~MyClass{	delete singleton;	singleton = NULL;}void MyClass::MyTestFunction(){	//nothing, because it''s only an example}


Then whenever you want to use the singleton do:

MyClass *XMyClass;XMyClass = new XMyClass;//Use this anywhere in your appMyClass::singleton->MyTestFunction();//Use this where ever XMyClass is accessableXMyClass->MyTestFunction();


I wrote all of that in Notepad just now so it might now be perfect, but it''s simple and it works. I use it in my project.

James Simmons
MindEngine Development
http://medev.sourceforge.net
I''m surprised no one has templated it yet. I''m too tired...but it''s a good idea
Brian J
Scott Bilas's singleton implementation is templated (you can google for it if you want it). It's actually a rather good implementation and is used in the Enginuity series. I was using it with a technique used by the OGRE engine that allows me to export the singleton function in a dll however I realized that for some very odd reason I could not use anything having to do with std:: from within the singleton'd class. Enginuity doesn't suffer from this problem because it doesn't use the export technique. I found the way I showed above to be much better.

James Simmons
MindEngine Development
http://medev.sourceforge.net

[edited by - neurokaotix on November 10, 2003 12:34:49 AM]
Thankyou all for helping, I''ve got a good grip on singletons now.

This topic is closed to new replies.

Advertisement