#include "stdafx.h"
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton &Instance()
{
if (_instance == NULL)
{
_instance = new Singleton();
}
return *_instance;
}
protected:
Singleton()
{
}
private:
static Singleton *_instance;
};
Singleton* Singleton::_instance = NULL; // This line is a must, or link error occurs
int _tmain(int argc, _TCHAR* argv[])
{
// Constructor is protected -- cannot use new
Singleton *s1 = &Singleton::Instance();
Singleton *s2 = &Singleton::Instance();
// Test for same instance
if (s1 == s2)
{
cout << "Objects are the same instances" << endl;
}
return 0;
}