1萨醒、懶漢式(1)
class Singleton {
public:
static Singleton* getInstance() {
if (_instance == nullptr) {
_instance = new Singleton();
}
return _instance;
}
private:
static Singleton* _instance;
};
Singleton* Singleton::_instance = nullptr;
- 懶加載烧栋,在需要的時候創(chuàng)建實例
- 線程不安全写妥,當A線程創(chuàng)建實例時,恰好B線程也在執(zhí)行當前代碼审姓,A線程和B線程都會創(chuàng)建一份實例
2珍特、懶漢式(2)
class Singleton {
public:
static Singleton* getInstance() {
lock_guard<mutex> lock(_mutex);
if (_instance == nullptr) {
_instance = new Singleton();
}
return _instance;
}
private:
static Singleton* _instance;
static mutex _mutex;
};
Singleton* Singleton::_instance = nullptr;
mutex Singleton::_mutex;
3魔吐、餓漢式
class Singleton {
public:
static Singleton* getInstance() {
return _instance;
}
private:
static Singleton* _instance = new Singleton();
};
- 編寫簡單扎筒,執(zhí)行效率高,線程安全
- 無論是否使用酬姆,都會創(chuàng)建實例嗜桌,會浪費資源
4、Meyers' Singleton(現(xiàn)在代碼里面使用的)
class Singleton {
public:
Singleton(const Singleton &) = delete;
Singleton& operator=(const Singleton &) = delete;
static Singleton& getInstance() {
// 靜態(tài)局部變量
static Singleton instance;
return instance;
}
private:
Singleton() {}
};
- 靜態(tài)局部變量只會在第一次函數(shù)調(diào)用時初始化辞色,后續(xù)再次調(diào)用不會初始化實例
- 懶加載骨宠,只有在使用到時,才會創(chuàng)建實例
- 返回引用可以防止指針被delete或者被置空