c++ 单例模式


1
一个类只有一个实例:一般创建实例的代码可能会涉及到线程安全方面的问题,需注意,代码如下: 2 #include <iostream> 3 using namespace std; 4 #define HUNGRY_MODE // 饿汉模式,在一开始就创建 5 #define LAZY_MODE // 懒汉模式,在需要的时候才创建 6 class DSingletonMode{ 7 private: 8 static DSingletonMode *m_pSingletonInstance; 9 private: 10 DSingletonMode(){ /* Constructor */} 11 DSingletonMode(const DSingletonMode &other){ 12 // Copy constructor 13 } 14 DSingletonMode operator = (const DSingletonMode &other){ 15 // Assignment constructor 16 } 17 public: 18 // Get singleton mode object, and it can have parameters 19 static DSingletonMode *GetSingletonInstance(void){ 20 /* 21 These code has thread self question 22 */ 23 #ifdef LAZY_MODE 24 Lock(); 25 if (NULL == m_pSingletonInstance) 26 { 27 /* code */ 28 m_pSingletonInstance = new DSingletonMode(); 29 } 30 unlock(); 31 #endif 32 33 return (m_pSingletonInstance); 34 } 35 void OtherFunction(/* Parameters */){ 36 // Do something 37 cout<<"I can do anything!"<<endl; 38 } 39 } 40 #ifdef HUNGRY_MODE 41 static DSingletonMode *DSingletonMode::m_pSingletonInstance = new DSingletonMode(); 42 #else 43 static DSingletonMode *DSingletonMode::m_pSingletonInstance = NULL; 44 #endif

对于上述编译可能存在错误,因为类的静态变量需要放在源文件而不是头文件进行显式的初始化;

还有对于懒汉模式可能存在线程安全问题,所以对于创建单例那里需要进行上锁设置,对于windows可以采用临界区,可用如下代码代替:

// 添加类的私有成员
private:
    CCriticalSection m_section; 

// 改写返回实例的函数
static DSingletonMode *GetSingletonInstance(void){
            /*
            These code has thread self question
             */
            #ifdef LAZY_MODE
            // Lock(); 实现线程安全(realize thread safe)
            m_section.Lock(0);
            if (NULL == m_pSingletonInstance)
            {
                /* code */
                m_pSingletonInstance = new DSingletonMode();
            }
            // unlock();
            m_section.Unlock();
            #endif
            
            return (m_pSingletonInstance);
        }

临界区可以对某段代码进行加锁,直到释放权限。

以后会进行改进!

posted @ 2014-01-08 17:56  殇 离  阅读(148)  评论(0编辑  收藏  举报