c++ 单例模式

本文对比了两种常见的模板类单例模式实现方式,并通过示例代码展示了它们的使用方法和区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

template<class Type>
class Singleton
{
protected:
    Singleton(){}
    ~Singleton(){}

    class EConstuct
    {
    public:
        EConstuct()
        {
            
        }
        ~EConstuct()
        {
            if(Singleton::object !=NULL)
                delete Singleton::object;

        }
    };


public:
    static Type *object;
    static EConstuct m_cons;

    static inline Type& instance()
    {
        if(object ==NULL)
        {
            printf("have construct \n");
            object = new Type();
        }
        return *object;
    }

};
template<class Type> Type* Singleton<Type>::object =NULL;

网上的一般是这种模式,今天发现了另外一种模式,比较新颖

template<class Type>
class Singleton2
{
public:
    Singleton2()
    {
        m_nReference++;
        if(m_object ==NULL)
        {
            m_object = new Type();
        }
    }
    virtual ~Singleton2()
    {
        m_nReference --;
        if(m_nReference==0)
        {
            printf("Deleted \n");
            delete m_object;
            m_object =NULL;
            breakPoint();
        }
    }


    Type *instance()
    {
        return m_object;
    }

    
    Type* operator ->() const
    {
        return m_object;
    }

    
private:

    static Type *m_object;
    static int m_nReference;
};

template<class Type>
Type* Singleton2<Type>::m_object =NULL;
template<class Type>
int Singleton2<Type>::m_nReference =0;

使用起来也方便

int main(int argc, char* argv[])
{
    Singleton2<Rte>  tmp ;
    tmp->data =10;

    printf("%d \n",tmp->data);
    Singleton2<Rte> temp;
    temp->data =40;
    printf("%d \n",tmp->data);
    temp.instance()->data =10;
    printf("%d \n",tmp->data);
    //printf("%f \n",Abc::instance().data);
    //Abc::instance().data =20;
    //printf("%f \n",Abc::instance().data);
    
    
    
    int gg;
    scanf("%d",&gg);
    
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值