# include <iostream>
# include <numeric>
template <typename T>
class Singleton
{
//friend class foo; //not acceptable
protected:
Singleton() {}
virtual ~Singleton() {}
public:
static T& Instance()
{
static T obj ;
return ( obj ) ;
}
private:
Singleton(const Singleton &s);
Singleton &operator = (const Singleton &s);
};
class foo : public Singleton < foo >
{
int x ;
protected:
//foo() {}
public :
void SetX ( int const in )
{ x = in ; }
int GetX () const { return ( x ) ; }
};
int main()
{
foo f;
f.SetX ( 5 ) ;
foo& ff = foo::Instance();
std::cout << ff.GetX() << std::endl;
std::cin.get();
}
# include <iostream>
// This is how a Gamma Singleton would instantiate its object.
template <class T> struct CreateGamma {
static T* Create() { return new T; }
};
// This is how a Meyers Singleton would instantiate its object.
template <class T> struct CreateMeyers {
static T* Create() {
static T _instance;
return &_instance;
}
};
// This Singleton class accepts different creation policies.
template <class T, template<class> class CreationPolicy=CreateMeyers>
class Singleton {
public:
static T& Instance() {
if (!m_pInstance)
m_pInstance=CreationPolicy<T>::Create();
return *m_pInstance;
}
private:
Singleton(); // ctor hidden
~Singleton() { std::cout << "l" << std::endl; } // dtor hidden
Singleton(Singleton const&); // copy ctor hidden
Singleton& operator=(Singleton const&); // assign op hidden
static T* m_pInstance;
};
template <class T, template<class> class C> T* Singleton<T,C>::m_pInstance=0;
class MyClass {
int xx ;
public:
MyClass()
: xx ( 0 )
{}
void foo ( int x )
{
xx = x;
std::cout << "MyClass::foo(" << std::hex << xx << ") called" << std::endl;
}
int bar()
{
std::cout << "MyClass::bar called" << std::endl;
return ( xx ) ;
}
~MyClass ()
{ std::cout << "~MyClass::MyClass" << std::endl; }
};
typedef Singleton<MyClass, CreateGamma> MyClassLeaking;
void test3()
{
int val=MyClassLeaking::Instance().bar();
MyClassLeaking::Instance().foo(++val);
MyClassLeaking::Instance().bar();
}
typedef C_Singleton< lets_see > LetsSeeInstance;
int main() {
MyClass mC ;
std::cout << "using leaking singleton" << std::endl;
MyClassLeaking::Instance().foo(0x0100);
std::cout << "test3" << std::endl;
test3();
std::cout << "test3" << std::endl;
test3();
//std::cin.get();
}
// This is how a Gamma Singleton would instantiate its object.
template <class T> struct CreateGamma : T {
static T* Create() { return new CreateGamma; }
};
why do want derive from singleton class? actually it is some contradiction cause for any derived class you may have one instance. so the baseclass isnt a singleton anymore.