#include <iostream>
#include <pthread.h>
template<typename T>
class Singleton
{
public:
static T* getInstance()
{
pthread_once( &_once_control, init );
return _value;
}
private:
static void init()
{
_value = new T();
}
Singleton() = default;
Singleton(const Singleton&) = delete; // non construction-copyable
Singleton & operator=(const Singleton&) = delete; // non copyable
virtual ~Singleton();
static pthread_once_t _once_control;
static T* _value;
};
template<typename T>
pthread_once_t Singleton<T>::_once_control = PTHREAD_ONCE_INIT;
template<typename T>
T* Singleton<T>::_value = NULL;
// mya *p = Singleton< mya >::getInstance();
class mya
{
public:
mya(){};
~mya(){};
};
int main(int argc, const char * argv[])
{
mya *p = Singleton< mya >::getInstance();
mya *q = Singleton<mya>::getInstance();
if( p == q )
std::cout<<"singleton success"<< std::endl;
else
std::cout<<"singleton failure"<< std::endl;
// insert code here...
std::cout << "Hello, World!\n";
return 0;
}
#include <pthread.h>
template<typename T>
class Singleton
{
public:
static T* getInstance()
{
pthread_once( &_once_control, init );
return _value;
}
private:
static void init()
{
_value = new T();
}
Singleton() = default;
Singleton(const Singleton&) = delete; // non construction-copyable
Singleton & operator=(const Singleton&) = delete; // non copyable
virtual ~Singleton();
static pthread_once_t _once_control;
static T* _value;
};
template<typename T>
pthread_once_t Singleton<T>::_once_control = PTHREAD_ONCE_INIT;
template<typename T>
T* Singleton<T>::_value = NULL;
// mya *p = Singleton< mya >::getInstance();
class mya
{
public:
mya(){};
~mya(){};
};
int main(int argc, const char * argv[])
{
mya *p = Singleton< mya >::getInstance();
mya *q = Singleton<mya>::getInstance();
if( p == q )
std::cout<<"singleton success"<< std::endl;
else
std::cout<<"singleton failure"<< std::endl;
// insert code here...
std::cout << "Hello, World!\n";
return 0;
}