C++单例的完美实现

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

  1. 怎么控制创建类的过程
  2. 怎么兼容多线程
  3. 怎么在合适时机自动析构
  4. 怎么自动初始化mutex和释放
  5. 禁止拷贝,复制拷贝和等号运算符
// 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;
}

以下是饿汉实现,来自http://www.cnblogs.com/qiaoconglovelife/p/5851163.html

class singleton
{
protected:
    singleton()
    {}
private:
    static singleton* p;
public:
    static singleton* initance();
};
singleton* singleton::p = new singleton;
singleton* singleton::initance()
{
    return p;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值