在C++中,單例模式可以通過以下幾種方式來實現:
class Singleton {
public:
static Singleton& getInstance() {
static Singleton instance;
return instance;
}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
private:
Singleton() {}
};
class Singleton {
public:
static Singleton& getInstance() {
static Singleton instance;
return instance;
}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
private:
Singleton() {}
};
class Singleton {
public:
static Singleton& getInstance() {
static Singleton instance;
return instance;
}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
private:
Singleton() {}
static Singleton instance;
};
Singleton Singleton::instance;
以上是幾種常見的單例模式實現方法,其中餓漢式單例模式在程序啟動時即創建實例,懶漢式單例模式在第一次調用時創建實例,使用靜態成員變量的單例模式也是在第一次調用時創建實例。在實現單例模式時需要注意線程安全性和資源釋放等問題。