饿汉模式
类实例化就会占用内存,浪费资源,效率高,不存在线程安全问题。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
class Singleton{ Singleton() { } static Singleton* m_instance_ptr; public : static Singleton* get_instance() { return m_instance_ptr; } }; Singleton* Singleton::m_instance_ptr = new Singleton(); int main(){ Singleton* instance1 = Singleton::get_instance(); Singleton* instance2 = Singleton::get_instance(); return 0; } |
懒汉模式
延迟加载,节省资源,效率低,存在线程安全问题。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
class Singleton { Singleton() { } static Singleton* m_instance_ptr; public : static Singleton* get_instance() { if (m_instance_ptr == nullptr) m_instance_ptr = new Singleton(); return m_instance_ptr; } }; Singleton* Singleton::m_instance_ptr = nullptr; int main(){ Singleton* instance1 = Singleton::get_instance(); Singleton* instance2 = Singleton::get_instance(); return 0; } |
锁 + 智能指针
线程安全(锁)+ 内存回收(智能指针)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
#include <iostream> #include <memory> #include <mutex> class Singleton { public : typedef std::shared_ptr<Singleton> Ptr; static Ptr get_instance() { if (m_instance_ptr == nullptr) { std::lock_guard<std::mutex> lk(m_mutex); if (m_instance_ptr == nullptr) m_instance_ptr = std::shared_ptr<Singleton>( new Singleton); } return m_instance_ptr; } private : Singleton() {} static Ptr m_instance_ptr; static std::mutex m_mutex; }; Singleton::Ptr Singleton::m_instance_ptr = nullptr; std::mutex Singleton::m_mutex; int main(){ Singleton::Ptr instance1 = Singleton::get_instance(); Singleton::Ptr instance2 = Singleton::get_instance(); return 0; } |
局部静态变量
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
class Singleton { public : Singleton( const Singleton&)= delete ; static Singleton& get_instance() { static Singleton instance; return instance; } private : Singleton() {} }; int main() { Singleton& instance1 = Singleton::get_instance(); Singleton& instance2 = Singleton::get_instance(); return 0; } |
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注服务器之家的更多内容!
原文链接:https://blog.csdn.net/weixin_43976081/article/details/121972988