溫馨提示×

c++單例模式怎么優(yōu)化

c++
小億
104
2023-10-13 10:15:01
欄目: 編程語言

在C++中,單例模式可以通過以下幾種方式進行優(yōu)化:

  1. 懶漢式改進:懶漢式單例模式在需要使用單例對象時才創(chuàng)建,但每次獲取單例對象都需要進行線程同步的判斷和加鎖操作,可以使用雙重檢查鎖定(Double-Checked Locking)的方式進行優(yōu)化。即在加鎖前后進行兩次判斷,第一次判斷是為了避免不必要的加鎖操作,第二次判斷是為了在第一次判斷通過后,避免多個線程同時創(chuàng)建實例。具體代碼如下:
class Singleton {
private:
static Singleton* instance;
static std::mutex mtx;
Singleton() {}
Singleton(const Singleton& other) = delete;
Singleton& operator=(const Singleton& other) = delete;
public:
static Singleton* getInstance() {
if (instance == nullptr) {
std::lock_guard<std::mutex> lock(mtx);
if (instance == nullptr) {
instance = new Singleton();
}
}
return instance;
}
};
Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mtx;
  1. 餓漢式改進:餓漢式單例模式在類加載時就創(chuàng)建單例對象,但可能會導(dǎo)致程序啟動慢,可以使用靜態(tài)局部變量的方式進行優(yōu)化。靜態(tài)局部變量在函數(shù)第一次被調(diào)用時初始化,避免了在程序啟動時就創(chuàng)建單例對象的開銷。具體代碼如下:
class Singleton {
private:
Singleton() {}
Singleton(const Singleton& other) = delete;
Singleton& operator=(const Singleton& other) = delete;
public:
static Singleton* getInstance() {
static Singleton instance;
return &instance;
}
};
  1. Meyers Singleton:Meyers Singleton是C++11標(biāo)準(zhǔn)引入的一種線程安全的單例模式實現(xiàn)方式,它利用了靜態(tài)局部變量的特性,確保了只有一個實例被創(chuàng)建,并且在多線程環(huán)境下也是安全的。具體代碼如下:
class Singleton {
private:
Singleton() {}
Singleton(const Singleton& other) = delete;
Singleton& operator=(const Singleton& other) = delete;
public:
static Singleton* getInstance() {
static Singleton instance;
return &instance;
}
};

以上是對C++單例模式進行優(yōu)化的幾種方式,具體選擇哪種方式,取決于具體的需求和使用場景。

0