Instance() in Singleton Class Question
I am curious to ask. Why do you need to use Instance() function?
You can always use Singleton() function and ~Singleton() function.
Execute Instance() function will start to execute Singleton() function
before it returns back to Instance() function. The program exited
before it will not execute ~Singleton() function. You must use
Terminate() function manually to clear dynamic memory otherwise leak
memory can occur. It is not worth practice.
Read Note 1 and Note 2 inside main() function. Note 2 does its own
job to execute ~Singleton() function before program exits. Note 2 is
always useful when you want to use only one instance (one object such
as keyboard, mouse, floppy drive, etc)...
#include <stdio.h>
#include <stdlib.h>
class Singleton
{
public:
static Singleton* Instance(); // Why do you need it?
void Terminate(); // Why do you need it?
static void Print();
//protected:
Singleton();
~Singleton();
private:
Singleton(const Singleton&);
Singleton& operator= (const Singleton&);
static Singleton* pinstance; // Why do you need it?
};
Singleton* Singleton::pinstance = 0;
Singleton* Singleton::Instance ()
{
if (pinstance == 0)
pinstance = new Singleton;
return pinstance;
}
void Singleton::Terminate ()
{
if (pinstance != 0)
{
delete pinstance;
pinstance = 0;
}
}
Singleton::Singleton()
{
printf("Constructor\n");
}
Singleton::~Singleton()
{
printf("Destructor\n");
}
void Singleton::Print()
{
printf("Test\n");
}
int main()
{
// Note 1
Singleton & ref = * Singleton::Instance();
ref.Print();
ref.Terminate();
// Note 2
Singleton s;
s.Print(); // ( Singleton::Print() is same as s.Print() )
system("pause"); // Function comes from Microsoft Visual C++ .Net
return 0;
}