-
單例指對象只能被創建一次,不可重複創建
-
利用C++ static 關鍵字實現靜態局部變量,即使重複聲明返回的也是第一次創建的對象
代碼:
int x = 20;
class Singleton
{
private:
Singleton() { val = x++; cout << "Obeject Create!\n"; } //私有構造函數,只能通過Get方法調用
~Singleton() { cout << "Object Delete!\n"; }
public:
int val;
static Singleton *GetInstance()
{
static Singleton ret; //static類型變量,僅在首次聲明時創建賦值
return &ret;
}
};
int main()
{
Singleton *s = Singleton::GetInstance();
cout << s->val << '\n'; //驗證
Singleton *s2 = Singleton::GetInstance();
cout << s->val << '\n';
return 0;
}
運行結果: