单例模式的完美写法

1、单线程使用的单例

#include <iostream>
using namespace std;


class testsingleton
{
private:
    testsingleton(){}; //构造函数
    testsingleton(const testsignton &){}; //拷贝构造
    testsingleton& operator=(const testsingleton&){}; //复制构造
    static testsingleton*  instance; //静态变量区
public:
    ~testsingleton();
    static testsingleton* getSingleton();

};
testsingleton* testsingleton::instance = nullptr;

testsingleton* testsingleton::getSingleton(){
    if ( nullptr == instance)
    {
        instance = new testsingleton();
    }
    return  instance;
}

int main(){
    testsingleton*  sign1 =  testsingleton::getSingleton();
    cout << "address1:"  << sign1   <<endl;
    testsingleton*  sign2 =  testsingleton::getSingleton();
    cout << "address2:"  << sign2   <<endl;
    return 0;
}

原理:
1、利用静态变量的全声明周期,保障单例全生命周期的可访问性。
2、利用私有化构造,拷贝,复制构造函数保障单例模式的唯一性。
缺点:
1、只能用于单线程情况,多线程可能存在多个实例
2、需要手动释放申请的内存。

2、互斥锁单例

#include <iostream>
#include <mutex>
#include <memory>
using namespace std;

class testsingleton
{
private:
    testsingleton(){}; //构造函数
    testsingleton(const testsingleton&){}; //拷贝构造
    testsingleton& operator=(const testsingleton&){}; //复制构造
    static testsingleton*  instance; //静态变量区
    static mutex m_mutex;
    static void destorySingleton(){   //释放单例内存
        if (nullptr != instance){
            delete instance;
            instance = nullptr;
        }
    }
public:
    static testsingleton* getSingleton();

};
testsingleton* testsingleton::instance = nullptr; //静态变量初始化
mutex testsingleton::m_mutex; //互斥锁初始化

testsingleton* testsingleton::getSingleton(){
    //lock_guard<mutex> lg(m_mutex);不在这里lock是因为单例只初始化一次,所有大多数情况下都是非空
    //这里加锁,每一次获取单例,都要上一次锁,有影响效率。尽管影响很小。
    if ( nullptr == instance)
    {
        lock_guard<mutex> lg(m_mutex);
        if (nullptr == instance)
        {
            instance = new testsingleton();
            atexit(destorySingleton); //退出时调用释放函数内存,也可以使用智能指针和内部类实现自动释放对象
        }
    }
    return  instance;
}

int main(){
    testsingleton*  sign1 =  testsingleton::getSingleton();
    cout << "address1:"  << sign1   <<endl;
    testsingleton*  sign2 =  testsingleton::getSingleton();
    cout << "address2:"  << sign2   <<endl;
    return 0;
}

优点:
1、双空检查,保障效率。
2、atexit做到自动释放内存(也可以使用智能指针和内部类实现自动释放对象)。
缺点:
1、仍然做不到100%线程安全。

2.1 new操作符步骤

instance = new testsingleton();
使用new操作符来分配对象内存时会经历三个步骤:
第一步:调用operator new 函数分配一块足够大的,原始的,未命名的内存空间以便存储特定类型的对象。
第二步:编译器运行相应的构造函数以构造对象,并为其传入初值。
第三步:将内存地址赋值给instance

2.2 多线程乱序执行

我们的代码都会汇编生成一条的汇编指令,代码执行即汇编指令执行。
而目前现多核心cpu并非逐条处理机器指令,机器指令会根据不同情况进行重排。
那么意味着new的执行步骤可能不按照我们看到的1->2->3执行,可能按照的是1->3->2执行。

2.3 互斥单例的线程不安全

在这里插入图片描述
从上面看出,如果new操作符第二步testsingleton的对象还未构造成功,但是线程1的执行时钟周期到了,切换到线程2执行。
线程2如果使用为构造成功的指针地址,去操作对象,那么程序就会崩溃。

Scott Meyers and 和Alexandrescu写的一篇文章里面专门分析了这种解决方案的问题C++ and the Perils of Double-Checked Locking

3、c++11 内存屏障单例

#include <iostream>
#include <mutex>
#include <memory>
#include <atomic>
using namespace std;

class testsingleton
{
private:
    testsingleton(){}; //构造函数
    testsingleton(const testsingleton&){}; //拷贝构造
    testsingleton& operator=(const testsingleton&){}; //复制构造
    static atomic<testsingleton*>  instance; //静态变量区
    static mutex m_mutex;
    static void destorySingleton(){   //释放单例内存
        testsingleton* tmp = instance.load(memory_order_relaxed);
        if (nullptr != tmp){
            delete tmp;
            tmp = nullptr;
        }
    }
public:
    static testsingleton* getSingleton();

};
atomic<testsingleton*> testsingleton::instance; //静态变量初始化
mutex testsingleton::m_mutex; //互斥锁初始化

testsingleton* testsingleton::getSingleton(){
    testsingleton* tmp = instance.load(memory_order_relaxed);
    atomic_thread_fence(memory_order_acquire); //获取内存屏障
    if ( nullptr == tmp)
    {
        lock_guard<mutex> lg(m_mutex);
        tmp = instance.load(memory_order_relaxed);
        if (nullptr == tmp)
        {
            tmp = new testsingleton();
            atomic_thread_fence(memory_order_release);//释放内存屏障,此间所有代码不会重排
            instance.store(tmp, memory_order_relaxed); 
            atexit(destorySingleton); 
        }
    }
    return tmp;
}

int main(){
    testsingleton*  sign1 =  testsingleton::getSingleton();
    cout << "address1:"  << sign1   <<endl;
    testsingleton*  sign2 =  testsingleton::getSingleton();
    cout << "address2:"  << sign2   <<endl;
    return 0;
}

方案优点:
1、多线程下不安全
方案确定:
1、代码太复杂

4、c++11 magic static单例

c++11 magic static 当变量在初始化的时候,并发进入声明语句,并发线程将会阻塞等待初始化结束

#include <iostream>
using namespace std;

class testsingleton
{
private:
    testsingleton(){}; //构造函数
    testsingleton(const testsingleton&){}; //拷贝构造
    testsingleton& operator=(const testsingleton&){}; //复制构造
public:
    static testsingleton& getSingleton();
};

testsingleton& testsingleton::getSingleton(){

    static testsingletoninstance; 
    return  instance;
}

int main(){
    testsingleton&  sign1 =  testsingleton::getSingleton();
    cout << "address1:"  << &sign1   <<endl;
    testsingleton&  sign2 =  testsingleton::getSingleton();
    cout << "address2:"  << &sign2   <<endl;
    return 0;
}

优点:
1、静态局部变量,自动释放内存
2、自带线程安全
3、代码简洁
缺点:
1、不能继承。

5、可继承的单例模板

#include <iostream>

using namespace std;

template <typename T>
class testsingleton
{
//protected保证构造函数可以被继承
protected:
    testsingleton(){}; //构造函数
    testsingleton(const testsingleton&){}; //拷贝构造
    testsingleton& operator=(const testsingleton&){}; //复制构造
    virtual ~testsingleton(){};
public:
    static T& getSingleton(){
        static T instance;
        return instance;
    }
};

class subsingleton : public testsingleton<subsingleton >{
    //友元保证能够访问子类的私有构造函数
    friend class testsingleton<subsingleton >;
private:
    subsingleton (){};
    subsingleton (const subsingleton &){};
    subsingleton & operator=(const subsingleton &){};
};

int main(){
    susubsingleton&  sign1 =  testsingleton<subsingleton >::getSingleton();
    cout << "address1:"  << &sign1   << endl;
    subsingleton &  sign2 =  testsingleton<subsingleton >::getSingleton();
    cout << "address2:"  << &sign2   <<endl;
    return 0;
}

这样完美吗?
1、susubsingleton采用的是恶汉模式,恶汉模式的缺点就是启动就初始化,未使用就占用资源

6、call_once可继承的单例模板

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

template <typename T>
class testsingleton
{
//protected保证构造函数可以被继承
protected:
    testsingleton(){}; //构造函数
    testsingleton(const testsingleton &){}; //拷贝构造
    testsingleton& operator=(const testsingleton &){}; //复制构造
    
public:
    virtual ~testsingleton(){};
    static T* getSingleton(){
        static once_flag _once;
        call_once(_once, createInstance);
        return instance;
    }
private:
    static void createInstance(){
        instance = new T();
    }
    static T * instance;
};

template <typename T>
T * testsingleton<T>::instance = nullptr;

class subsingleton : public testsingleton<subsingleton>{
    //友元保证能够访问子类的私有构造函数
    friend class testsingleton<subsingleton>;
private:
    subsingleton(){};
    subsingleton(const subsingleton&){};
    subsingleton& operator=(const subsingleton&){};
};

int main(){
    subsingleton*  sign1 =  testsingleton<subsingleton>::getSingleton();
    cout << "address1:"  << sign1   << endl;
    subsingleton*  sign2 =  testsingleton<subsingleton>::getSingleton();
    cout << "address2:"  << sign2   <<endl;
    return 0;
}

这里完美吗?
1、createInstance()无法接收到参数

7、可变参数call_once可继承的单例模板

#include <iostream>
#include <mutex>
#include <memory>
#include <functional>

using namespace std;

template <typename T>
class testsingleton
{
//protected保证构造函数可以被继承
protected:
    testsingleton(){}; //构造函数
    testsingleton(const testsingleton &){}; //拷贝构造
    testsingleton& operator=(const testsingleton &){}; //复制构造
    
public:
    virtual ~testsingleton(){};
    template<class ...Args>
    static T* getSingleton(Args &&... in){
        static once_flag _once;
        call_once(_once, [&](){instance.reset(new T(forward<Args>(in)...));});
        return instance.get();
    }
private:
    static unique_ptr<T> instance;
};

template <typename T>
unique_ptr<T> testsingleton<T>::instance = nullptr;

class subsingleton : public testsingleton<subsingleton>{
    //友元保证能够访问子类的私有构造函数
    friend class testsingleton<subsingleton>;
private:
    subsingleton(){};
    subsingleton(int i){};
    subsingleton(const subsingleton&){};
    subsingleton& operator=(const subsingleton&){};
};

int main(){
    subsingleton*  sign1 =  testsingleton<subsingleton>::getSingleton();
    cout << "address1:"  << sign1   << endl;
    subsingleton*  sign2 =  testsingleton<subsingleton>::getSingleton();
    cout << "address2:"  << sign2   <<endl;
    subsingleton*  sign3 =  testsingleton<subsingleton>::getSingleton(1);
    cout << "address3:"  << sign3   << endl;
    subsingleton*  sign4 =  testsingleton<subsingleton>::getSingleton(2);
    cout << "address4:"  << sign4   <<endl;
    return 0;
}

8、总结

从单例模式看7可以认为是完美的,但是这个写法太重。其实大多我们使用第4种写法就足够了,简洁明了。
代码简洁才是我们应该追求的,模式不是目的。效率,简洁,易维护才是更重要的。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kingforyang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值