1. 懒汉式单例模式(Lazy
Singleton)
懒汉式单例牧师只有在第一次使用的时候才创建实例
1.1 实现代码
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| #include <iostream> #include <mutex>
class Singleton { public: static Singleton* getInstance() { std::call_once(initFlag, []() { instance = new Singleton(); }); return instance; }
Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete;
void showMessage() { std::cout << "Hello from Singleton!" << std::endl; }
private: Singleton() {} static Singleton* instance; static std::once_flag initFlag; };
Singleton* Singleton::instance = nullptr; std::once_flag Singleton::initFlag;
int main() { Singleton* singleton = Singleton::getInstance(); singleton->showMessage();
return 0; }
|
其中,getInstance
方法:使用std::call_once
来确保instance
只被初始化一次,即使在多线程环境下也是安全的。
2. 饿汉式单例模式
饿汉式单例模式在类加载的时候就创建好一个静态实例,不管之后是否会用到这个实例。在多线程下是线程安全的。
2.1 实现代码
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 27 28 29 30 31 32 33 34 35
| #include <iostream>
class Singleton { public: static Singleton* getInstance() { return instance; }
Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete;
void showMessage() { std::cout << "Hello from Singleton!" << std::endl; }
private: Singleton() {}
static Singleton* instance; };
Singleton* Singleton::instance = new Singleton();
int main() { Singleton* singleton = Singleton::getInstance(); singleton->showMessage();
return 0; }
|
Reference
- 【字节跳动】如何在C++中实现单例模式?@Lynn77-QAQ https://www.bilibili.com/video/BV1NWs4ezEn5/?spm_id_from=333.1007.top_right_bar_window_history.content.click&vd_source=243ce9423fb82c395b4e9e6bf321ae0c