单例,智能指针

以下为单例头文件
csingleton.h

#ifndef CSINGLETON_H
#define CSINGLETON_H

#include “QAtomicPointer”
#include “QReadWriteLock”
#include “QMutex”
#include “QDebug”

template

class Singleton
{
public:
static T& getInstance(void);

private:
Singleton();//forbid
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);

QReadWriteLock  internalMutex;
static QMutex mutex;
static QAtomicPointer m_pInstance;

};

template
QAtomicPointerSingleton::m_pInstance;

template
QMutex Singleton::mutex(QMutex::Recursive);

template
T& Singleton::getInstance(void)
{
#ifndef Q_ATOMIC_POINTER_TEST_AND_SET_IS_ALWAYS_NATIVE
if(!QAtomicPointer::isTestAndSetNative())
#endif

        QMutexLocker locker(&mutex);// safe
        if(m_pInstance.testAndSetOrdered(0,0))
        {
            m_pInstance.testAndSetOrdered(0,new T);
        }
        
        return *m_pInstance.load();

}

#endif // CSINGLETON_H

使用该单例:
(1)类的定义
#include “csingleton.h”
class CTestControl: public QObject
{
Q_OBJECT
public:
explicit CTestControl(QObject *parent = 0);
~CTestControl(void);
}
typedef Singleton<CTestControl> SCDltUtility; // Singleton definition

(2)使用例子
CTestControl::getInstance();

你可能感兴趣的:(工具类使用,智能指针,单例)