Possible Duplicate:
C++ Singleton design pattern.
How can I create only one instance of a class and share that instance with all my header and source files without using a singleton? Can you provide a simple example?
Possible Duplicate:
C++ Singleton design pattern.
How can I create only one instance of a class and share that instance with all my header and source files without using a singleton? Can you provide a simple example?
You can do this:
class Sample
{
/*** your code **/
public:
Sample();
void DoWork();
int GetValue();
/*** other functions ***/
};
Sample & OneInstance()
{
static Sample instance;
return instance;
}
//Use OneInstance everywhere like this
OneInstance().DoWork();
Note Sample
is not a Singleton, but you can use OneInstance()
function as if it's one and the same instance of Sample
, which you use everywhere!
You can use it to initialize some global variables also like this:
int g_SomeValue= OneInstance().GetValue();
which cannot be done with global static
instance of Sample
. That is because of this:
I'd advice against sharing anything whenever you can avoid it, because sharing makes concurrency hard. If you don't care about concurrency then you should pass your object around as an extra parameter to functions. Globals are usually a bad idea and Singletons are usually mere globals with a fancy dress.