在C++中,使用靜態(tài)局部變量實(shí)現(xiàn)單例模式是一種簡潔且類型安全的方法。以下是實(shí)現(xiàn)步驟:
new
操作符創(chuàng)建對象。以下是實(shí)現(xiàn)單例模式的C++代碼示例:
#include <iostream>
#include <memory>
class Singleton {
public:
// 獲取Singleton類的唯一實(shí)例
static Singleton& getInstance() {
// 靜態(tài)局部變量instance在首次調(diào)用getInstance時(shí)初始化
static Singleton instance;
return instance;
}
// 刪除復(fù)制構(gòu)造函數(shù)和賦值操作符,防止復(fù)制單例對象
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
private:
// 私有構(gòu)造函數(shù),防止外部通過new操作符創(chuàng)建對象
Singleton() {
std::cout << "Singleton class created." << std::endl;
}
// 靜態(tài)私有成員變量,用于保存唯一實(shí)例
static Singleton instance;
};
// 初始化靜態(tài)成員變量
Singleton Singleton::instance;
int main() {
Singleton& singleton1 = Singleton::getInstance();
Singleton& singleton2 = Singleton::getInstance();
// 比較兩個(gè)引用是否指向同一實(shí)例
if (&singleton1 == &singleton2) {
std::cout << "Both instances are the same." << std::endl;
} else {
std::cout << "Instances are different." << std::endl;
}
return 0;
}
上述代碼實(shí)現(xiàn)了一個(gè)線程安全的單例模式。若需要支持多線程環(huán)境,可以使用C++11標(biāo)準(zhǔn)中的std::call_once
和std::once_flag
來確保靜態(tài)局部變量只被初始化一次,從而實(shí)現(xiàn)線程安全的單例模式。