社区养老,泊头吧,兰晓霞
饿汉模式是线程安全的
class singleton { public: static singleton* getinstance()//获取对象实例的唯一接口 { if (_inst == null) { _inst = new singleton; } return _inst; } void print() { cout << "singleton : " << _a << endl; } private: singleton()//防止构造函数创建对象 :_a(0) {} singleton& operator=(const singleton&) = delete; singleton(const singleton&) = delete; int _a; static singleton* _inst;//指向实例化的指针定义成静态成员 }; singleton* singleton::_inst = null;
加入raii机制,避免死锁的出现
class singleton { public: static singleton* getinstance()//获取对象实例的唯一接口 { if (null == _inst)//只有在创建实例的时候才进行加锁提高效率 { lock_guardlock(_mtx); if (_inst == null) { _inst = new singleton; } } return _inst; } void print() { cout << "singleton : " << _a << endl; } private: singleton()//防止构造函数创建对象 :_a(0) {} singleton& operator=(const singleton&) = delete; singleton(const singleton&) = delete; int _a; static singleton* _inst;//指向实例化的指针定义成静态成员 static mutex _mtx;//保证安全的互斥锁 }; singleton* singleton::_inst = null; mutex singleton::_mtx;
添加双检查机制来提高效率
添加内存栅栏技术来防止由于提升效率而打乱执行的顺序
对单例模式的释放,下面这种方法是有问题的
最好是调用atexit回调机制,在main函数结束完毕后再进行释放
class singleton { public: static singleton* getinstance()//获取对象实例的唯一接口 { if (null == _inst)//只有在创建实例的时候才进行加锁提高效率 { lock_guardlock(_mtx); if (_inst == null) { singleton* tmp = new singleton; memorybarrier();//内存栅栏技术 _inst = tmp; } } return _inst; } void print() { cout << "singleton : " << _inst << endl; } static void dellinstance() { lock_guardlock(_mtx); if (_inst) { cout << "delete " << endl; delete _inst; _inst = null; } } private: singleton()//防止构造函数创建对象 :_a(0) {} singleton& operator=(const singleton&) = delete; singleton(const singleton&) = delete; int _a; static singleton* _inst;//指向实例化的指针定义成静态成员 static mutex _mtx;//保证安全的互斥锁 }; singleton* singleton::_inst = null; mutex singleton::_mtx;
但是在特定情况下会出现问题
class singleton { public: static singleton& getinstance() { assert(_inst); return *_inst; } void print() { cout << "singleton : " << _inst << endl; } private: singleton() :_a(0) {} int _a; singleton& operator=(const singleton&) = delete; singleton(const singleton&) = delete; static singleton* _inst; }; singleton* singleton::_inst = new singleton;
class singleton { public: static singleton& getinstance() { static single _inst; return *_inst; } void print() { cout << "singleton : " << _inst << endl; } private: singleton() :_a(0) {} int _a; singleton& operator=(const singleton&) = delete; singleton(const singleton&) = delete; static singleton* _inst; }; singleton* singleton::_inst = null;
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
如何在没有core文件的情况下用dmesg+addr2line定位段错误
用QT制作3D点云显示器——QtDataVisualization
网友评论