C++单例的完美实现

314 阅读1分钟

这应该是懒汉模式完美单例了:


怎么控制创建类的过程

怎么兼容多线程

怎么在合适时机自动析构

怎么自动初始化mutex和释放

禁止拷贝,复制拷贝和等号运算符

// test.17.10.6.单例模式.cpp : 定义控制台应用程序的入口点。

//


#include "stdafx.h"

//#include <windows.h>

#include <pthread.h>



class CWMDL

{

private:

CWMDL(){}

static CWMDL* m_c ;//可以自动释放

// 禁止拷贝--复制构造函数和等号运算符声明为私有的,并且不提供实现。

CWMDL(const CWMDL& other);

CWMDL& operator=(const CWMDL& other);

public:

static CWMDL* Create()

{

if (nullptr==m_c)

{

printf("似乎未创建\r\n");

pthread_mutex_lock(&mutex);//双判断多线程加速

if (nullptr==m_c)

{

printf("确定未创建\r\n");

m_c = new CWMDL();

}

else

{

printf("其实创建了\r\n");

}

pthread_mutex_unlock(&mutex);


}

else

{

printf("已经创建\r\n");

}

return m_c;

}


class CGarbo // 它的唯一工作就是在析构函数中删除CSingleton的实例

{

public:

~CGarbo()

{

pthread_mutex_destory(&mutex);

if (CWMDL::m_c)

delete CWMDL::m_c;

}

};

static CGarbo Garbo; // 定义一个静态成员,在程序结束时,系统会调用它的析构函数

static pthread_mutex_t mutex;



};

CWMDL* CWMDL::m_c = nullptr;


pthread_mutex_t CWMDL::mutex = PTHREAD_MUTEX_INITIALIZER;//静态初始化




unsigned int __stdcall WorkThread(void*)

{

CWMDL* p = CWMDL::Create();

return 0;

}



int _tmain(int argc, _TCHAR* argv[])

{



//CRITICAL_SECTION x = [](){CRITICAL_SECTION cs_tmp;InitializeCriticalSection(&cs_tmp);return cs_tmp;};


/*

因为是单类,只有一个类指针

我认为 主动释放类的话(即调用delete),多线程 可能多次调用,所以我们要让它自动释放


实验之。


*/

const static int hdNumber = 20;

HANDLE hd[hdNumber] = {0};

for (int i =0;i<hdNumber;++i)

{

_beginthreadex(NULL,0,WorkThread,0,NULL,0);


}

WaitForMultipleObjects(hdNumber,hd,TRUE,-1);


Sleep(-1);




return 0;

}

以下是饿汉实现,来自www.cnblogs.com/qiaoconglov…


class singleton

{

protected:

singleton()

{}

private:

static singleton* p;

public:

static singleton* initance();

};

singleton* singleton::p = new singleton;

singleton* singleton::initance()

{

return p;

}