#include <QAtomicPointer>
#include <QMutex>
#include <memory>
#include <stdlib.h>
using namespace std;
template <class T>
class QSingleTon
{
public:
static T* instance(QObject* parent = 0)
{
#ifdef Q_ATOMIC_POINTER_TEST_AND_SET_IS_ALWAYS_NATIVE
if(!QAtomicPointer<T>::isTestAndSetNative())
#endif
{
QMutexLocker locker(&mutex);
if(m_pInstance.testAndSetOrdered(0,0))
{
m_pInstance.testAndSetOrdered(0,new T(parent));
atexit(deinstance);
}
}
return m_pInstance;
}
static void deinstance()
{
if(m_pInstance != NULL)
{
delete m_pInstance;
m_pInstance = NULL;
}
}
private:
QSingleTon(){}
QSingleTon(const QSingleTon & );
QSingleTon & operator = (const QSingleTon & );
private:
static QMutex mutex;
static QAtomicPointer<T> m_pInstance;
}
template <class T> QMutex QSingleTon<T>::mutex;
template <class T> QAtomPointer<T> QSingleTon<T>::m_pInstance = NULL;
#endif