面试手搓单例模式C++

C++代码如下:

#include <iostream>
using std::cout;
using std::endl;
//懒汉式
class SingletonLazy{
public:
    static SingletonLazy& getinstance(){
        static SingletonLazy m_instance;
        return m_instance;
    }
public:
    SingletonLazy(const SingletonLazy&) = delete;//禁止拷贝构造函数的调用
    SingletonLazy(SingletonLazy&&) = delete;//禁止移动构造函数的调用
    SingletonLazy& operator=(const SingletonLazy&) = delete;//禁止拷贝赋值操作符的调用
    SingletonLazy& operator=(SingletonLazy&&) = delete;//禁止移动赋值操作符的调用
private:
    SingletonLazy(){
        cout<<"ConstructorLazy called"<<endl;
    }
    ~SingletonLazy(){
        cout<<"DestructorLazy called"<<endl;
    }
};
//饿汉式
class SingletonHungry{
public:
    static SingletonHungry& getinstance(){
        return m_instance;
    }
public:
    SingletonHungry(const SingletonHungry&) = delete;
    SingletonHungry(SingletonHungry&&) = delete;
    SingletonHungry& operator=(const SingletonHungry&) = delete;
    SingletonHungry& operator=(SingletonHungry&&) = delete;
private:
    static SingletonHungry m_instance;
    SingletonHungry(){
        cout<<"ConstructorHungry called"<<endl;
    }
    ~SingletonHungry(){
        cout<<"DestructorHungry called"<<endl;
    }
};
SingletonHungry SingletonHungry::m_instance;
int main(){
    SingletonLazy& instance_1=SingletonLazy::getinstance();
    SingletonHungry& instance_2=SingletonHungry::getinstance();
    return 0;
}

代码解释:

由于在main函数之前初始化,所以没有线程安全的问题。但是潜在问题在于no-local static对象(函数外的static对象)在不同编译单元中的初始化顺序是未定义的。也即,static Singleton m_instance;和static Singleton& getInstance()⼆者的初始化顺序不确定,如果在初始化完成之前调⽤ getInstance() ⽅法会返回⼀个未定义的实例。
这是最推荐的一种单例实现方式:
1.通过局部静态变量的特性保证了线程安全 (C++11, GCC > 4.3, VS2015支持该特性)。
2.不需要使用共享指针,代码简洁,不需要使用互斥锁,没有双重检查锁定模式的风险。
3.注意在使用的时候需要声明单例的引用 SingletonPattern_V3& 才能获取对象。

运行结果:

ConstructorHungry called
ConstructorLazy called
DestructorLazy called
DestructorHungry called

分析运行结果:

1.ConstructorHungry called:饿汉式单例在类加载时初始化。
2.ConstructorLazy called:懒汉式单例在第一次调用 getinstance() 时初始化。
3.DestructorLazy called 和 DestructorHungry called:析构函数按照与构造函数相反的顺序被调用。

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值