单例模式

本文深入探讨了饿汉模式和懒汉模式在C++中的实现方式,通过具体代码展示了两种模式下单例对象的创建过程。饿汉模式在类加载时就创建实例,而懒汉模式则在首次调用时创建,更注重资源的有效利用。

饿汉模式

/*
#include<iostream>

using namespace std;


class Test 
{
public:
    static Test*  Getinstance()//只能以指针返回,其他不行。static调用约定不是thiscall
    {
        return  m_instance;
    }
private:
    Test()//将构造和拷贝构造写在私有下
    {};
    Test(const Test & rhs)
    {};
    static Test * m_instance;                                 
};



Test *  Test :: m_instance = new Test();    //static成员变量必须初始化


int main()
{
    Test *  a  = Test ::  Getinstance();
    Test *  b = Test ::  Getinstance();
    cout<< a <<" --- "<<b<<endl;
}
*/


懒汉模式

#include<iostream>
#include<mutex>
/*
using namespace std;

 mutex m;

class Test 
{
public:
    static Test *  Getinstance()//只能以指针返回,其他不行。static调用约定不是thiscall
    {
        if(NULL == m_instance)//双重锁机制,保证在创建对象后不在进行加解锁,提高CPU效率,
        {
            m.lock();
            if(NULL == m_instance)
            {
                m_instance = &Test();
            }
            m.unlock();
        }
        return  m_instance;
    }
private:
    Test()//将构造和拷贝构造写在私有下
    {};
    Test(const Test & rhs)
    {};
    static Test * m_instance;                                 
};



Test *  Test :: m_instance = NULL;    //static成员变量必须初始化


int main()
{
    Test *  a  = Test ::  Getinstance();
    Test *  b = Test ::  Getinstance();
    cout<< a <<" --- "<<b<<endl;
}
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值